zoukankan      html  css  js  c++  java
  • Python脚本

    控制CPU使用率

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    """
    运行命令:python 脚本名.py -c 核心数 -t 时间
    -c 不加该参数默认使用所有核心
    -t 数值越小,CPU使用率越高,一般设置0.3
    脚本默认执行2小时后随机睡眠10~30分钟继续执行
    """
    import time, random
    from time import clock
    import argparse
    from multiprocessing import Process
    from multiprocessing import cpu_count
    import math
    
    def exec_func(bt):
        bl = 0
        while True:
            if bl == 1:
                sj = random.randint(600, 1800)
                time.sleep(sj)
            start_time = time.time()
            while True: 
                for i in range(0, 9600000):
                    pass
                time.sleep(bt)
                stop_time = time.time()
                end = stop_time - start_time
                if int(end) >= 7200:
                   bl = 1
                   break
    
    
    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('
    ====================占用CPU核数{}.===================='.format(cpu_logical_count))
    #    print('
    资源浪费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("手工结束!")
    

    参考文档:https://www.cnblogs.com/yhleng/p/11891246.html

    查看CPU使用率

    top -n 1|grep -v grep|grep -Eo "^.Cpu.*us"

    本文来自博客园,作者:MegaloBox,转载请注明原文链接:https://www.cnblogs.com/cpw6/p/15467341.html

  • 相关阅读:
    10. Regular Expression Matching
    9. Palindrome Number (考虑负数的情况)
    8. String to Integer (整数的溢出)
    7. Reverse Integer (整数的溢出)
    LeetCode Minimum Size Subarray Sum
    LeetCode Course Schedule II
    Linux 文件缓存 (一)
    LeetCode Tries Prefix Tree
    Linux : lsof 命令
    LeetCode Binary Tree Right Side View
  • 原文地址:https://www.cnblogs.com/cpw6/p/15467341.html
Copyright © 2011-2022 走看看