如何在C ++中使用clock()

如何在C++调用clock()

例如,我想testing线性search花费多less时间来查找数组中的给定元素。

 #include <iostream> #include <cstdio> #include <ctime> int main() { std::clock_t start; double duration; start = std::clock(); /* Your algorithm here */ duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout<<"printf: "<< duration <<'\n'; } 

另一种解决scheme是可移植的,具有更高的精度,自C ++ 11以来,就是使用std::chrono

这里是一个例子:

 #include <iostream> #include <chrono> typedef std::chrono::high_resolution_clock Clock; int main() { auto t1 = Clock::now(); auto t2 = Clock::now(); std::cout << "Delta t2-t1: " << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << " nanoseconds" << std::endl; } 

在ideone.com上运行这个给了我:

 Delta t2-t1: 282 nanoseconds 

clock()返回自程序启动以来的时钟滴答数。 有一个相关的常量, CLOCKS_PER_SEC ,它告诉你在一秒钟内有多less时钟滴答。 因此,你可以testing像这样的任何操作:

 clock_t startTime = clock(); doSomeOperation(); clock_t endTime = clock(); clock_t clockTicksTaken = endTime - startTime; double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC; 

也许你可能会对这样的计时器感兴趣:H:M:S。 毫秒。

Linux操作系统中的代码:

 #include <iostream> #include <unistd.h> using namespace std; void newline(); int main() { int msec = 0; int sec = 0; int min = 0; int hr = 0; //cout << "Press any key to start:"; //char start = _gtech(); for (;;) { newline(); if(msec == 10) { ++sec; msec = 0; } if(sec == 60) { ++min; sec = 0; } if(min == 60) { ++hr; min = 0; } cout << hr << " : " << min << " : " << sec << " . " << msec << endl; ++msec; usleep(100000); } return 0; } void newline() { cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; } 
 #include <iostream> #include <ctime> #include <cstdlib> //_sleep() --- just a function that waits a certain amount of milliseconds using namespace std; int main() { clock_t cl; //initializing a clock type cl = clock(); //starting time of clock _sleep(5167); //insert code here cl = clock() - cl; //end point of clock _sleep(1000); //testing to see if it actually stops at the end point cout << cl/(double)CLOCKS_PER_SEC << endl; //prints the determined ticks per second (seconds passed) return 0; } //outputs "5.17"