How to occupy 80% CPU consistently?

2020-03-01 05:59发布

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 triggers under specific CPU utilization conditions
For this purpose I can assume that the machine is otherwise idle.

What's a robust and possibly OS independent way to do this?

3条回答
祖国的老花朵
2楼-- · 2020-03-01 06:06

There is no such thing as occupying the CPU 80% of the time. The CPU is always either being used, or idle. Over some period of time, you can get average usage to be 80%. Is there a specific time period you want it to be averaged over? This pseudo-code should work across platforms and over 1 second have a CPU usage of 80%:

while True:
    startTime = time.now()
    while date.now() - startTime < 0.8:
        Math.factorial(100) // Or any other computation here
    time.sleep(0.2)
查看更多
【Aperson】
3楼-- · 2020-03-01 06:13

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 <stdlib.h>
#include <signal.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

#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;
}
查看更多
放荡不羁爱自由
4楼-- · 2020-03-01 06:22

The trick is that if you want to occupy 80% of CPU, keep the processor busy for 0.8 seconds (or 80% of any time interval. Here I take it to be 1 second), then let it sleep for 0.2 seconds, though it is advisable not to utilize the CPU too much, or all your processes will start running slow. You could try around 20% or so. Here is an example done in Python:

import time
import math
time_of_run = 0.1
percent_cpu = 80 # Should ideally replace this with a smaller number e.g. 20
cpu_time_utilisation = float(percent_cpu)/100
on_time = time_of_run * cpu_time_utilisation
off_time = time_of_run * (1-cpu_time_utilisation)
while True:
    start_time = time.clock()
    while time.clock() - start_time < on_time:
        math.factorial(100) #Do any computation here
    time.sleep(off_time)
查看更多
登录 后发表回答