Hi,
is there any way one can determine the current CPU frequency?
I was trying to figure out a way to do this but couldn't find a way that works. My approach was to use the TSC (Time Stamp Counter), but with the tickless feature in the kernel the TSC gets unstable and can't be used for frequency calculation anymore.
Here's a draft of this idea (though on my systems with tickless enabled the calculated frequency is absolutely wrong):
Code:
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
unsigned long long int rdtsc(void)
{
unsigned long long int x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
}
int main()
{
struct timezone tz;
struct timeval tvstart, tvstop;
unsigned long long int cycles[2];
unsigned long microseconds;
int mhz;
memset(&tz, 0, sizeof(tz));
gettimeofday(&tvstart, &tz);
cycles[0] = rdtsc();
gettimeofday(&tvstart, &tz);
usleep(250000);
gettimeofday(&tvstop, &tz);
cycles[1] = rdtsc();
gettimeofday(&tvstop, &tz);
microseconds = ((tvstop.tv_sec-tvstart.tv_sec)*1000000) + (tvstop.tv_usec-tvstart.tv_usec);
mhz = (int) (cycles[1]-cycles[0]) / microseconds;
printf("%i MHz\n",mhz);
return 0;
}
The idea is to read the TSC, wait a small amount of time and read the TSC again. TSCnow-TSCstart / waited_time will return the CPU frequency provided the TSC is stable.
With tickless this gets all messed up and I can't come up with any other idea...
Peter