本文记录如何使用C/C++进行计时操作。
void timing()
{
time_t start,stop;
start = time(NULL);
foo(); // do something
stop = time(NULL);
printf("Time:%ld\n",(stop-start));
clock_t start2,stop2; // high resolution
start2 = time(NULL);
foo(); // do something
stop2 = time(NULL);
printf("Time:%f\n",(stop2-start2)/CLOCKS_PER_SEC);
}
C++11中添加了<chrono>
库,专门用来计时。
#include <iostream>
#include <chrono>
using 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;
}