这是计算 CPU 时间的代码,但它不正确,因为当我使用gettimeofday时,它会给我以毫秒为单位的正确时间。我在一个处理器上运行我的进程,它的时钟运行在 800MHz。我对rdtsc的了解如下:
- Rdtsc 返回周期数
使用这些周期数,可以计算给定时钟速率(800 MHZ)的 CPU 时间
unsigned long long a,b; unsigned long cpuMask; cpuMask = 2; // bind to cpu 1 if(!sched_setaffinity(0, sizeof(cpuMask), &cpuMask)) fprintf(stderr,"Running on one core!\n"); setpriority(PRIO_PROCESS, 0, 20); struct timeval t1, t2; double elapsedTime; int i=0; // start timer gettimeofday(&t1, NULL); a = rdtsc(); sleep(20); //for(;i<1000000;i++); //fprintf(stderr,"%d\n",i); gettimeofday(&t2, NULL); b = rdtsc(); printf("a:%llu\n", a); printf("b:%llu\n", b); double val = ((b-a)/800000); fprintf(stderr,"Time 1st through rdtsc in msec:%f\n\nSubtraction:%llu\n\n", val,b-a); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms fprintf(stderr,"Time through gettimeofday in ms:%f\n\n", elapsedTime);