您的位置:首页 > 其它

【性能测试】验证程序运行时所占用的时间Cycle

2013-11-14 16:46 1006 查看
1、cpu 频率为3.1MHz 说明1s的时间会发生3.1 * 100 0000 cycle,即1个cycle占用1/3.1MHz s即 1个cycle 占用 1/3.1us

 The speed of a computer processor, or
CPU, is determined by the clock cycle, which is the amount of time between two pulses of an
oscillator. Generally speaking, the higher number of pulses per second, the faster the computer processor will be able to process information. The
clock speed is measured in
Hz, typically either megahertz (MHz) or gigahertz (GHz).
For example, a 4GHz processor performs 4,000,000,000 clock cycles per second.

Computer processors can execute one or more instructions per clock cycle, depending on the type of processor. Early computer processors and slower processors can only execute on instruction per clock cycle, but faster, more advanced processors can execute
multiple instructions per clock cycle, processing data more efficiently.

2、例子程序如下:

#include "stdio.h"

#include "time.h"

#include "string.h"

#define rdtsc(low,high) __asm__ \

 __volatile__("rdtsc" : "=a" (low), "=d" (high))

typedef unsigned long long cycles_t;

unsigned long long get_cycles()

{
unsigned low, high;
unsigned long long val;
rdtsc(low,high);
val = high;

val = (val << 32) | low; //将 low 和 high 合成一个 64 位值
return val;

}

double get_cpu_mhz(void)

{
FILE* f;
char buf[2048];
double mhz = 0.0;
char *p = NULL;

f = fopen("/proc/cpuinfo","r"); //打开 proc/cpuinfo 文件
if (!f)
return 0.0;
while(fgets(buf, sizeof(buf), f)) {
float m;
int rc;
p = strstr(buf,"cpu MHz:");
if(NULL == p)
{

memset(buf,0,2048);
continue;
}
p = p + sizeof("cpu MHz  :");
*(p + 8) = '\0';
rc = sscanf(p,"%f",&m);
//rc = sscanf(p, "cpu MHz         : %f\n", &m); //读取 cpu MHz
if(rc ==0)
{
continue;
}
if (mhz == 0.0) {
mhz = m;
break;
}
}
fclose(f);

return mhz; //返回 HZ 值

}

int main()

{
float mhz;
mhz = get_cpu_mhz();
cycles_t c1, c2;
float tmp;
for(;;)
{
c1 = get_cycles(); 
sleep(1);
c2 = get_cycles();

 //c2 和 c1 的差值应该为 1000000us,即 1 秒

  tmp = (float)(c2 -c1);
printf("%f %lf ,1 sec = %f usec\n", tmp,mhz,tmp / mhz); 
}

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: