突然想起来这个编程之美上的问题,按照网上的写法在ARM(v7, dual core)平台上试了下,均不能达到效果,后来解决了,以下为QNX上的代码:
/* * A small program used to take 50% CPU cost. */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> int main(int argc, char *argv[]) { int i; unsigned int res; clock_t time_start; struct timespec sres; //get clock resolution frist. if (clock_getres(CLOCK_REALTIME, &sres) == -1) { perror("clock get resolution"); return EXIT_FAILURE; } printf("Resolution is %u micro seconds.\n", res = (sres.tv_nsec / 1000)); while (1){ // work a little time(10*clock resolution) time_start = clock(); // 1s == clock()/CLOCKS_PER_SEC 1000000 while (clock() - time_start <= 10 * res){ i++; } // sleep the same time usleep(10 * res); } return EXIT_SUCCESS; }
主题思想就是让程序工作一会然后再休息一会。
具体原因就是工作和休息的时间与时间精度不符,调整后运行结果如下:

原文:https://www.cnblogs.com/Freeee/p/11599455.html