How to occupy 80% CPU consistently?

后端 未结 3 474
鱼传尺愫
鱼传尺愫 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 02:09

    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)
    

提交回复
热议问题