Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to occupy 80% CPU consistently?

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?

like image 273
shoosh Avatar asked Aug 28 '11 16:08

shoosh


People also ask

Is 80% CPU usage good?

CPUs are designed to run safely at 100% CPU utilization. However, you'll want to avoid these situations whenever they cause perceptible slowness in games.

Is 90% CPU usage normal?

If your CPU use temporarily spikes to 90% or 100%, that's normal if you're doing intensive tasks like high-end gaming or graphic design. So long as your CPU calms down after you're done, there's nothing to worry about.

Is 70% CPU usage high?

It is normal for it to be high because the processor is not doing much at the moment. So, if your System Idle process is using 60% - 70% of your CPU, it means you're actually using 40% - 30% of it. Was this reply helpful? No the System Idle Process is only using 20-30% when running no or very few programs.


2 Answers

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)
like image 158
Andrew C Avatar answered Sep 20 '22 00:09

Andrew C


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;
}
like image 28
Chris Dodd Avatar answered Sep 19 '22 00:09

Chris Dodd