首页 > 编程语言 > 详细

python控制cpu使用率

时间:2019-11-19 19:15:46      阅读:594      评论:0      收藏:0      [点我收藏+]

以下亲测可行。

 

使用方法:命令行模式

runing.py -c 2 -t 0.01

-c 指定cpu核数:不指定-c参数默认为所有核数。

-t 数值越大,cpu使用率越低。

 

runing.py

"""
runing 100
"""
import time
from time import clock
import argparse
from multiprocessing import Process
from multiprocessing import cpu_count
import math

def exec_func(bt):

    while True: 
        for i in range(0, 9600000):
            pass
        time.sleep(bt)



if __name__ == "__main__":

    parse = argparse.ArgumentParser(description=runing)

    parse.add_argument(
        "-c",
        "--count",
        default= cpu_count(),
        help=cpu count
        )

    parse.add_argument(
        "-t",
        "--time",
        default= 0.01,
        help=cpu time
        )


    args = parse.parse_args()

    cpu_logical_count = int(args.count)

    cpu_sleep_time = args.time

    try:
        cpu_sleep_time = int(args.time)
    except ValueError:
        try:
            cpu_sleep_time = float(args.time)
        except ValueError as ex:
            raise ValueError(ex)

    print(\n====================占用CPU核数{}.====================.format(cpu_logical_count))
    print(\n资源浪费starting......)
    print(cpu_sleep_time)

    try:

        p = Process(target=exec_func, args=("bt",))

        ps_list = []

        for i in range(0, cpu_logical_count):
            ps_list.append(Process(target=exec_func, args=(cpu_sleep_time,)))

        for p in ps_list:
            p.start()

        for p in ps_list:
            p.join()
    except KeyboardInterrupt:
        print("手工结束!")

 

python控制cpu使用率

原文:https://www.cnblogs.com/yhleng/p/11891246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!