使用rdtsc进行秒计算 [英] Seconds calculation using rdtsc

查看:254
本文介绍了使用rdtsc进行秒计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用于计算CPU时间的代码,但它不正确,因为当我使用 gettimeofday 时,它为我提供了正确的时间(以毫秒为单位).我在一个处理器上运行我的进程,其时钟运行在800MHz.我对rdtsc的了解如下:

Here is the code to calculate CPU time but it's not correct because when I use gettimeofday it gives me correct time in ms. I am running my process on one processor and its clock runs at 800MHz. My knowledge about rdtsc is as follows:

  • Rdtsc返回周期数
  • 使用这些周期数,可以在给定时钟频率(800 MHZ)的情况下计算CPU时间

  • Rdtsc returns number of cycles
  • Using those # of cycles one can calculate the CPU time given the clock rate (800 MHZ)

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);

推荐答案

理论上,不能保证rdtsc与CPU周期有很强的关系,例如1个周期等于3个rdtsc单位.实际上,假设具有constant_tsc功能,在Intel CPU上rdtsc单位等于(1秒/max_frequency_of_cpu).因此,第一个问题是: max 频率是800MHz还是当前频率?

In theory, there is no guarantee that rdtsc would have strong relation to CPU cycles, e.g. 1 cycle may equal to 3 rdtsc units. In practice, rdtsc unit equals to (1 second / max_frequency_of_cpu) on Intel CPUs assuming constant_tsc feature is present. So, first question is: is 800MHz is max frequency or is it current frequency?

无论如何,clock_gettime(CLOCK_MONOTONIC_RAW, ...)是您最有可能要使用的.我的理解是,它准确地映射到时间戳记计数器,并且在引导OS时使用系统时钟进行了校准.

Anyway, clock_gettime(CLOCK_MONOTONIC_RAW, ...) is what most likely you want to use. My understanding is that it is mapped exactly to timestamp counter and is calibrated with system clock when OS is booted.

(是的,您的代码完全可以在我的i7-3635QM上正常工作.)

(And yes, your code works exactly as expected on my i7-3635QM).

这篇关于使用rdtsc进行秒计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆