1,实例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static unsigned cyc_high=0;
static unsigned cyc_low=0;
//rstsc指令访问计数器,高32为保存在%edx,低32位保存在%ax
void access_counter( unsigned* hi, unsigned* lo )
{
asm("rdtsc; movl %%edx,%0; movl %%eax,%1"
:"=r" (*hi),"=r" (*lo)
:
: "%edx", "%eax");
}
void start_counter()
{
access_counter( &cyc_high, &cyc_low );
}
double get_counter()
{
unsigned ncyc_high,ncyc_low;
unsigned high_num,low_num,borrow;
double result;
access_counter( &ncyc_high, &ncyc_low );
low_num=ncyc_low-cyc_low;
borrow=( low_num<0 );
high_num=ncyc_high-cyc_high;
result=(double)high_num*(1<<30)*4+low_num;
if(result<0)
fprintf(stderr,"Error: counter returns neg value: %.0f\n",result);
return result;
}
double get_mhz(int sleeptime)
{
double rate;
start_counter();
sleep(sleeptime);
rate=get_counter()/(1e6*sleeptime);
return rate;
}
int main()
{
double mhz;
mhz=get_mhz(3);
printf("CPU Time Frequency: %.0f MHZ\n",mhz);
start_counter();
//测量代码段
printf("%.0f",get_counter());
return 0;
}
分享到:
评论