Yebangyu's Blog

Fond of Concurrency Programming , Distributed System and Machine Learning

Linux下C++程序计时方法

最近简单学习了下LinuxC++程序计时的一些函数和方法,总结如下。没啥insight了。

方法一:

如果是想统计某个程序的运行时间,那么可以使用

time ./a.out

方法二:

如果是想对某个函数或者语句进行计时,那么有别的方法。比如说,gettimeofday函数。直接贴示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <sys/time.h>
void f()
{
  //...
}
int main()
{
  struct timeval t1, t2;
  gettimeofday(&t1, NULL);
  f();
  gettimeofday(&t2, NULL);
  //那么函数f运行所花的时间为
  //deltaT = (t2.tv_sec-t1.tv_sec) * 1000000 + t2.tv_usec-t1.tv_usec 微秒
  return 0;
}

gettimeofday只能精确到微秒,并且它受系统时钟的影响(它的原理就是通过读取系统时钟,因此当计时的这段时间里有其他程序修改了系统时钟,那么结果将不准确)。

如果想精确到纳秒呢?继续往下看:

方法三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <time.h>
void f()
{
  //...
}
int main()
{
  timespec t1, t2;
  clock_gettime(CLOCK_MONOTONIC, &t1);
  f();
  clock_gettime(CLOCK_MONOTONIC, &t2);
  //那么f所花时间为
  //deltaT = (t2.tv_sec - t1.tv_sec) * 10^9 + t2.tv_nsec - t1.tv_nsec 纳秒
  return 0;
}

这里说的都是wall clock,如果想获得cpu执行时间,以及了解clock_gettime参数的解释和可能的取值,可以man一下。