Implement CPU burner using Python

For the modern computers, they mostly have multiple CPU cores. We can use Python’s multiprocessing module to automatically get the number of CPU cores. Then we use this module to spawn corresponding processes to generate load on all the CPU cores concurrently.

On each CPU core, we can perform arithmetic operation for the fraction of a second and then sleep for the rest of a second. For example, if you want to have 85% CPU utilization, each CPU core can do the arithmetic operation for 0.85 second and sleep 0.15 second.

Implementation

import sys
import math
import time
import multiprocessing

def cpu_burner(duration, util):
    start_time = time.time()
    for i in range(0, duration):
        while time.time() - start_time < util / 100.00:
            math.pow(2, 10)
        time.sleep(1 - util / 100.00)
        start_time += 1


if __name__ == "__main__":
    if len(sys.argv) == 3:
        processes = []
        for _ in range(multiprocessing.cpu_count()):
            p = multiprocessing.Process(
                target=cpu_burner, args=(int(sys.argv[1]), int(sys.argv[2]))
            )
            p.start()
            processes.append(p)

        for process in processes:
            process.join()
    else:
        print("Usage:\n python %s duration util" % __file__)

Burn the CPU cores

# python cpu_burner.py 60 85

Verify the CPU utilization

# mpstat -P ALL 2
04:46:49 AM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
04:46:51 AM  all   84.93    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.07
04:46:51 AM    0   85.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.00
04:46:51 AM    1   84.42    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.58
04:46:51 AM    2   85.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.00
04:46:51 AM    3   85.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.00
04:46:51 AM    4   85.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.00
04:46:51 AM    5   85.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.00
04:46:51 AM    6   85.43    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   14.57
04:46:51 AM    7   84.92    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   15.08

Reference