lil*_*llq 79 c performance timer timing
以高分辨率和可移植性为代码部分计时的最佳方法是什么?
/* Time from here */
ProcessIntenseFunction();
/* to here. */
printf("Time taken %d seconds %d milliseconds", sec, msec);
Run Code Online (Sandbox Code Playgroud)
是否有一个具有跨平台解决方案的标准库?
Sop*_*ert 135
我认为这应该有效:
#include <time.h>
clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);
Run Code Online (Sandbox Code Playgroud)
Mar*_*son 21
gettimeofday()可能会做你想要的.
如果您使用的是英特尔硬件,请按以下步骤阅读CPU实时指令计数器.它将告诉您自处理器启动以来执行的CPU周期数.这可能是您可以获得性能测量的最细粒度,最低开销的计数器.
请注意,这是CPU周期数.在linux上,您可以从/ proc/cpuinfo获取CPU速度并除以获得秒数.将其转换为double是非常方便的.
当我在我的盒子上运行时,我得到了
11867927879484732 11867927879692217 it took this long to call printf: 207485
这是英特尔开发人员指南,提供了大量细节.
#include <stdio.h>
#include <stdint.h>
inline uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax, %%eax\n"
"cpuid\n"
"rdtsc\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx");
return (uint64_t)hi << 32 | lo;
}
main()
{
unsigned long long x;
unsigned long long y;
x = rdtsc();
printf("%lld\n",x);
y = rdtsc();
printf("%lld\n",y);
printf("it took this long to call printf: %lld\n",y-x);
}
Run Code Online (Sandbox Code Playgroud)