利用python占用cpu,增加cpu利用率
有些时候需要服务器占用一些资源的时候(提高cpu利用率)
import time
import multiprocessingdef use_cpu():# 获取当前时间current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print(f"开始利用CPU - {current_time}")# 利用CPU# 在这里添加一些计算密集型的操作# 创建一个进程池,最大进程数为4pool = multiprocessing.Pool(processes=6)nums = []for _ in range(6):random_seed = random.randint(20, 45)*1000000# 定义需要计算的参数列表nums.append(random_seed)# 使用进程池并行计算results = pool.map(calculate, nums)# 输出结果print(results)current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print(f"结束利用CPU - {current_time}")del pool# 定义一个计算密集型函数
def calculate(num):random_repeat = random.randint(80, 200)for _ in range(random_repeat):result = 0for i in range(num):result += ireturn resultimport random
if __name__ == '__main__':# 每隔十分钟执行一次while True:use_cpu()random_int = random.randint(60, 600) ##1-10mintime.sleep(random_int) # 600秒等于十分钟