如何在C中找到我的程序部分的执行时间?

Ste*_*her 16 c timing

我试图找到一种方法来获取C中一段代码的执行时间.我已经尝试过来自time.h的time()和clock(),但似乎time()返回秒和时钟()似乎给我几毫秒(或几厘秒?)我想要更精确的东西.有没有办法我能以至少微秒的精度抓住时间?

这只需要能够在Linux上编译.

And*_*mbe 15

你提到clock()time()-您寻找的gettimeofday()?这将填充a struct timeval,其中包含秒和微秒.

当然,实际分辨率取决于硬件.


Phi*_*hly 12

对于它的价值,这里只是一些宏:

#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);
Run Code Online (Sandbox Code Playgroud)

然后使用它:

main() {
  START;
  // Do stuff you want to time
  STOP;
  PRINTTIME;
}
Run Code Online (Sandbox Code Playgroud)

来自http://ctips.pbwiki.com/Timer


Tho*_*n79 11

你想要一个探查器应用程序.

搜索SO和搜索引擎的关键字:linux profiling

  • Profiler提供统计信息,这与实际测量不同. (2认同)