首页 > 其他 > 详细

P001 写个CPU占用恒定在50%的程序

时间:2019-09-27 18:14:20      阅读:112      评论:0      收藏:0      [点我收藏+]

突然想起来这个编程之美上的问题,按照网上的写法在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;
}

主题思想就是让程序工作一会然后再休息一会。

具体原因就是工作和休息的时间与时间精度不符,调整后运行结果如下:

技术分享图片

 

P001 写个CPU占用恒定在50%的程序

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!