记录代码所花费的时间

Recording time taken by code

本文关键字:时间 代码 记录      更新时间:2023-10-16

我使用下面的函数来查找代码所花费的时间。

  #include <sys/time.h>
  struct timeval start, end;
  gettimeofday(&start,NULL);   
  //mycode   
  gettimeofday(&end,NULL);
  cout<<" time taken by my code: "<<((end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec ) / 1000.0<<" msec"<<endl;

我观察到,尽管我的代码运行了2个小时,但上面函数报告的时间是1213毫秒。我不明白为什么会发生这种事。也有一种方法,我可以记录我的代码所花费的时间在小时正确

我最好的猜测是time_t (tv_sec的类型)在您的系统上是32位的,并且(end.tv_sec - start.tv_sec) * 1000000溢出。

你可以通过确保你不使用32位算术来测试这个理论:

(end.tv_sec - start.tv_sec) * 1000000LL

话虽如此,我建议使用c++ 11 <chrono>库来代替:

 #include <chrono>
  auto t0 = std::chrono::system_clock::now();
  //mycode
  auto t1 = std::chrono::system_clock::now();
  using milliseconds = std::chrono::duration<double, std::milli>;
  milliseconds ms = t1 - t0;
  std::cout << " time taken by my code: " << ms.count() << 'n';

<chrono>库有一个不变量,即在+/- 292年内,"预定义的"持续时间都不会溢出。在实践中,只有nanoseconds会很快溢出,其他持续时间的范围要大得多。每个持续时间都有静态::min()::max()函数,您可以使用它们来查询每个持续时间的范围。

<chrono>的原始提案有一个不错的教程部分,可能是一个有用的介绍。它只是有点过时。monotonic_clock现在被称为steady_clock。我相信这是它唯一缺少的重要更新。

你在哪个平台上做这个?如果它是类似Linux/unix的,那么最简单的非侵入式方法就是从命令行中使用time命令。你运行的代码是不是单线程的?time.h中的一些函数(例如clock())返回每个内核的滴答数,这可能是您想要的,也可能不是。而在chrono中的新东西可能不像你喜欢的那样精确(前阵子我试图用chrono来测量纳秒的时间间隔,但我当时得到的最低时间间隔是300ns,这比我希望的精确得多)。

这部分基准测试过程可能有助于您的目的:

#include<time.h>
#include<cstdlib>
...
...
float begin = (float)clock()/CLOCKS_PER_SEC;
...
//do your bench-marking stuffs
...
float end = (float)clock()/CLOCKS_PER_SEC;
float totalTime = end - begin;
cout<<"Time Req in the stuffs: "<<totalTime<<endl;
注意:此过程是chrono
的简单替代方法。

如果您是在linux上,并且您想要计时的代码主要是程序本身,那么您可以通过将其作为参数传递给time命令并查看'elapsed time'行来计时程序。

/usr/bin/time -v <your program's executable>
例如:

/usr/bin/time -v sleep 3                                                                                         .../home/aakashah/workspace/head/src/GroverStorageCommon
        Command being timed: "sleep 3"
        User time (seconds): 0.00
        System time (seconds): 0.00
        Percent of CPU this job got: 0%
        Elapsed (wall clock) time (h:mm:ss or m:ss): 0:03.00
        Average shared text size (kbytes): 0
        Average unshared data size (kbytes): 0
        Average stack size (kbytes): 0
        Average total size (kbytes): 0
        Maximum resident set size (kbytes): 2176
        Average resident set size (kbytes): 0
        Major (requiring I/O) page faults: 0
        Minor (reclaiming a frame) page faults: 165
        Voluntary context switches: 2
        Involuntary context switches: 0
        Swaps: 0
        File system inputs: 0
        File system outputs: 0
        Socket messages sent: 0
        Socket messages received: 0
        Signals delivered: 0
        Page size (bytes): 4096
        Exit status: 0