How to occupy 80% CPU consistently?

后端 未结 3 506
鱼传尺愫
鱼传尺愫 2021-01-04 01:16

I\'m looking for a way to occupy exactly 80% (or any other number) of a single CPU in a consistent manner.
I need this for some unit test that tests a component that tri

3条回答
  •  臣服心动
    2021-01-04 01:48

    Its pretty easy to write a program that alternately spins and sleeps to get any particular load level you want. I threw this together in a couple of minutes:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define INTERVAL    500000
    volatile sig_atomic_t   flag;
    void setflag(int sig) { flag = 1; }
    
    int main(int ac, char **av) {
        int load = 80;
        struct sigaction sigact;
        struct itimerval interval = { { 0, INTERVAL }, { 0, INTERVAL } };
        struct timespec pausetime = { 0, 0 };
        memset(&sigact, 0, sizeof(sigact));
        sigact.sa_handler = setflag;
        sigaction(SIGALRM, &sigact, 0);
        setitimer(ITIMER_REAL, &interval, 0);
        if (ac == 2) load = atoi(av[1]);
        pausetime.tv_nsec = INTERVAL*(100 - load)*10;
        while (1) {
            flag = 0;
            nanosleep(&pausetime, 0);
            while (!flag) { /* spin */ } }
        return 0;
    }
    

提交回复
热议问题