我編寫了一個簡單的程序來測量使用RDTSC指令的代碼執行時間。但我不知道我的結果是否正確,並且我的代碼有問題......我不知道如何驗證它。使用RDTSC指令在C中測量代碼執行時間
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#define N (1024*4)
unsigned cycles_low, cycles_high, cycles_low1, cycles_high1;
static __inline__ unsigned long long rdtsc(void)
{
__asm__ __volatile__ ("RDTSC\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t": "=r" (cycles_high), "=r" (cycles_low)::
"%rax", "rbx", "rcx", "rdx");
}
static __inline__ unsigned long long rdtsc1(void)
{
__asm__ __volatile__ ("RDTSC\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t": "=r" (cycles_high1), "=r" (cycles_low1)::
"%rax", "rbx", "rcx", "rdx");
}
int main(int argc, char* argv[])
{
uint64_t start, end;
rdtsc();
malloc(N);
rdtsc1();
start = (((uint64_t)cycles_high << 32) | cycles_low);
end = (((uint64_t)cycles_high1 << 32) | cycles_low1);
printf("cycles spent in allocating %d bytes of memory: %llu\n",N, end - start);
return 0;
}
您需要通過添加cpuid指令或使用rdtscp將序列化添加到rdtsc。請參閱英特爾有關進行測量的最佳做法的白皮書。 http://www.intel.com/content/www/us/en/embedded/training/ia-32-ia-64-benchmark-code-execution-paper.html。 – Imran
請勿使用'RDTSC'。使用「時鐘」或操作系統特定的功能。對於Linux閱讀[時間(7)](http://man7.org/linux/man-pages/man7/time.7.html),然後使用[clock_gettime(2)](http://man7.org/linux /man-pages/man2/clock_gettime.2.html) –
@BasileStarynkevitch感謝您的回覆。我正在研究內核2.4.37,我可否知道你推薦哪個函數來測量內核中的時間?謝謝你的時間。 – HuangJie