|
这里讨论的是计算时间间隔的计时。
大部分情况下gettimeofday是够用的,这里我说的是一种不通过系统调用的方法。
奔腾和它后继的CPU里有一个叫Time Stamp Counter ,TSC的64位寄存器,晶振每振一次它就会加1,例如一个400MHz的芯片,那么它就是每2.5纳秒更新一次。通过汇编指令rdtsc就可以读取它的值。所以,知道了CPU的频率,就可以精确计时,至于获取CPU的频率,我还没有查到,那位读过内核的给说一下。
我写了个简单的计算CPU频率的程序,由于用了gettimeofday,所以很不精确,仅供讨论。参考了linux的内核代码。
[code:1]
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#define rdtsc(low,high) \
__asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
int main (int argc, char** argv)
{
unsigned int high1, low1;
unsigned int high2, low2;
struct timeval t1, t2;
gettimeofday (&t1, NULL);
rdtsc(low1, high1);
/* 一秒的循环 */
while (1) {
gettimeofday (&t2, NULL);
if (t1.tv_sec<t2.tv_sec && t1.tv_usec<=t2.tv_usec)
break;
}
rdtsc(low2, high2);
printf ("%ld.%ld\n", t1.tv_sec, t1.tv_usec);
printf ("%ld.%ld\n", t2.tv_sec, t2.tv_usec);
if (low2<low1) {
low2 = 0xffffffff - low1 + low2;
high2 = high2 - high1 -1;
}
else {
high2 = high2 - high1;
low2 = low2 - low1;
}
printf ("%08x %08x\n", high2, low2);
return 0;
}
[/code:1]
linux计算386系列CPU频率的函数在arch/i386/kernel/timers/common.c |
|