# -*- coding: utf-8 -*-
import time
import random
# 精确度,1到4位小数,计算和sleep的基本单位
accuracy = 0.01
def test_random_time_cost():
"""
做100万次随机操作,计算每秒可随机的次数
"""
t = time.time()
for j in range(1000000):
random.random()
all_time_cost = time.time() - t
times_per_second = int(1000000 / all_time_cost)
return times_per_second
def force_cpu_source(cpu_percent):
times_per_second = test_random_time_cost()
c = int(times_per_second * accuracy)
while True:
# 每次循环随机进行计算或等待
if random.random() < cpu_percent:
for i in range(c):
random.random()
else:
time.sleep(accuracy)
if __name__ == '__main__':
# 指定CPU使用率
cpu_percent = 0.7
force_cpu_source(cpu_percent)
time.sleep的精确度受系统影响。
accuracy的值最好是0.1或者0.01。太小的值在time.sleep的时候会有很大误差。
平台 | accuracy | sleep次数 | 耗时 |
---|---|---|---|
腾讯云服务器 | 0.1 | 1000 | 100.1439 |
腾讯云服务器 | 0.01 | 1000 | 10.0862 |
腾讯云服务器 | 0.001 | 1000 | 1.0717 |
腾讯云服务器 | 0.0001 | 1000 | 0.1661 |
腾讯云服务器 | 0.00001 | 1000 | 0.07187 |
个人PC | 0.1 | 1000 | 109.0052 |
个人PC | 0.01 | 1000 | 15.5868 |
个人PC | 0.001 | 1000 | 15.5708 |
个人PC | 0.0001 | 1000 | 15.5952 |
个人PC | 0.00001 | 1000 | 15.6032 |