unw*_*ind 11
你需要高分辨率的计时器.
在Linux上,它gettimeofday()是一个不错的选择,它为您提供微秒级的分辨率.在Windows上,QueryPerformanceCounter()是典型的.确保多次运行您的功能,以获得稳定的读数.
适用于Linux的快速示例:
struct timeval t0, t1;
unsigned int i;
gettimeofday(&t0, NULL);
for(i = 0; i < 100000; i++)
function_to_measure();
gettimeofday(&t1, NULL);
printf("Did %u calls in %.2g seconds\n", i, t1.tv_sec - t0.tv_sec + 1E-6 * (t1.tv_usec - t0.tv_usec));
Run Code Online (Sandbox Code Playgroud)
您当然会调整计数(100,000)以匹配函数的性能.最好是函数真的需要一段时间才能运行,否则循环和/或函数调用开销可能占主导地位.
小智 5
你好,我会给你一个例子并解释它:
#include <stdio.h>
#include <time.h>
int main(void)
{
clock_t start_clk = clock();
/*
put any code here
*/
printf("Processor time used by program: %lg sec.\n", \
(clock() - start_clk) / (long double) CLOCKS_PER_SEC);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:程序使用的处理器时间:4.94066e-324 秒。
时间.h:
声明 clock_t 是一个算术(您可以像我在示例中那样对此值进行数学运算)时间值。基本上把任何代码放在注释所在的地方。
CLOCKS_PER_SEC 是time.h 中声明的一个宏,以它为分母将值转换为秒。
出于两个原因,必须将其强制转换为 long double:
| 归档时间: |
|
| 查看次数: |
7304 次 |
| 最近记录: |