在不同的 Ubuntu x86 LINUX 机器(包括 x86 虚拟机)上进行的重复测试均确认 250/秒,或实际使用 CPU 时的 4ms 间隔。在这个时代,这真的是正确的吗?测试程序包括在下面
示例结果:
./itimer 200 3
freq = 200
timeout = 3
When over, you should see 599 firings
PERF timer fired 599 times
VIRTUAL timer fired 599 times
./itimer 500 3
freq = 500
timeout = 3
When over, you should see 1499 firings
PERF timer fired 749 times
VIRTUAL timer fired 749 times
测试程序
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
struct itimerval mrVal;
struct itimerval timeout;
int ncalls = 0;
int nvcalls = 0;
void killer(int signum)
{
// Off by a few because we don't stop the timers,
// but good enough for testing purposes
printf("PERF timer fired %d times\n", ncalls);
printf("VIRTUAL timer fired %d times\n", nvcalls);
exit(0);
}
void interval_handler(int signum)
{
ncalls += 1;
}
void virtual_handler(int signum)
{
nvcalls += 1;
}
static double keeper = 12.345;
int main(int argc, char **argv)
{
if (argc < 3) {
printf("Usage: itimer freq seconds-to-run\n");
exit(1);
}
int freq = atoi(argv[1]);
int sleepsex = atoi(argv[2]);
printf("freq = %d\n", freq);
printf("timeout = %d\n", sleepsex);
printf("When over, you should see %d firings\n",
(freq * sleepsex) - 1);
timeout.it_interval.tv_sec = sleepsex;
timeout.it_interval.tv_usec = 0;
timeout.it_value = timeout.it_interval;
mrVal.it_interval.tv_sec = 0;
mrVal.it_interval.tv_usec = 1000000 / freq;
mrVal.it_value = mrVal.it_interval;
if(signal(SIGPROF, interval_handler) == SIG_ERR) {
printf("HOSER!\n");
}
if(signal(SIGVTALRM, virtual_handler) == SIG_ERR) {
printf("HOSER!\n");
}
if(signal(SIGALRM, killer) == SIG_ERR) {
printf("HOSER!\n");
}
if(signal(SIGINT, killer) == SIG_ERR) {
printf("HOSER!\n");
}
setitimer(ITIMER_PROF, &mrVal, 0);
setitimer(ITIMER_VIRTUAL, &mrVal, 0);
#if 1
// Use CPU. Otherwise, the PERF timer doesn't go off
// Trivial floating point stuff that counts good enough
// as work
setitimer(ITIMER_REAL, &timeout, 0);
while(1) {
double d = keeper;
d/=1.3773;
d*=1.3777;
keeper = d;
}
#else
sleep(sleepsex);
killer(0);
#endif
}