首页 > 解决方案 > 如何操纵python脚本以一定百分比对CPU施加压力?

问题描述

我在网上找到了一个模拟CPU负载的python脚本。问题是它模拟了 100% 的负载。我希望能够根据用户输入设置百分比参​​数。我怎么能在这里做到这一点?这是代码:

#!/usr/bin/env python
"""
Produces load on all available CPU cores

Updated with suggestion to prevent Zombie processes
Linted for Python 3
Source: 
insaner @ https://danielflannery.ie/simulate-cpu-load-with-python/#comment-34130
"""
from multiprocessing import Pool
from multiprocessing import cpu_count

import signal

stop_loop = 0


def exit_chld(x, y):
    global stop_loop
    stop_loop = 1


def f(x):
    global stop_loop
    while not stop_loop:
        x*x


signal.signal(signal.SIGINT, exit_chld)

if __name__ == '__main__':
    processes = cpu_count()
    print('-' * 20)
    print('Running load on CPU(s)')
    print('Utilizing %d cores' % processes)
    print('-' * 20)
    pool = Pool(processes)
    pool.map(f, range(processes))

我还想删除进程以释放使用量。

标签: pythoncpu-usagestress-testing

解决方案


推荐阅读