测量程序性能的方法
程序性能的测量主要有两种方法:
- 循环计数,统计时间法
- cycle统计法
循环计数,时间统计法
int i = 0;
struct timeval start, end;
int loop = 100000;
gettimeofday(&start, NULL);
for (i = 0; i < loop; i++) {
test_example();
}
gettimeofday(&end, NULL);
uint64_t time_cost = ((end.tv_sec - start.tv_sec) * 1000000 + \
end.tv_usec - start.tv_usec);
printf("cost time: %ld us, %.2f\n", time_cost, loop / (time_cost * 1.0) * 1000000);
cycle统计法
uint64_t rdtsc()
{
unsigned long a, d;
asm volatile ("cpuid; rdtsc" : "=a" (a), "=d" (d) : : "ebx", "ecx");
return a | ((uint64_t)d << 32);
}
begin = rdtsc();
test_example();
end = rdtsc();
printf("Cost: %ld cycles.\n", end - begin);