考虑以下代码:
#include <stdio.h> #include <time.h> #include <math.h> // Compile with gcc -lrt -lm -o test_clock test_clock.c #define CLOCK CLOCK_MONOTONIC int main(int argc, char** argv) { double temp, elapsed; int j; struct timespec requestStart, requestEnd, req; // Pseudo-sleep clock_gettime(CLOCK, &requestStart); temp = 0; for(j=0; j < 40; j++) temp += sin(j); clock_gettime(CLOCK, &requestEnd); elapsed = ( requestEnd.tv_sec - requestStart.tv_sec ) / 1e-6 + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / 1e3; printf("Elapsed: %lf us\n", elapsed); // Nanosleep clock_gettime(CLOCK, &requestStart); req.tv_nsec = 5000; req.tv_sec = 0; clock_nanosleep(CLOCK, 0, &req, NULL); clock_gettime(CLOCK, &requestEnd); elapsed = ( requestEnd.tv_sec - requestStart.tv_sec ) / 1e-6 + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / 1e3; printf("Elapsed: %lf us\n", elapsed); }
在我的2.6.32系统上,结果是
Elapsed: 5.308000 us Elapsed: 69.142000 us
我同意这很可能是因为nanosleep()要求内核重新安排进程。如何避免这种情况?我想保留对CPU的所有权,并在精确的时间内闲置。
如果您希望应用程序能够尽可能准确地“hibernate”,请首先将应用程序置于实时状态
看看http://www.drdobbs.com/184402031