Created
July 31, 2019 07:45
-
-
Save wkgcass/c176b2af1f7947f9e3dc41ddee133f44 to your computer and use it in GitHub Desktop.
set_cpu_usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import random | |
import time | |
TARGET = -1 | |
ADJUST_THRESHOLD = 100 | |
CNT_MIN = 0 | |
SLP_MIN = 1 | |
SLP_MAX = 10 | |
cnt_top = 0 | |
slp = 1 | |
cnt = 0 | |
adjust_cnt = 0 | |
last_cpu_total = 0L | |
last_cpu_idle = 0L | |
def get_cpu_usage(): | |
global last_cpu_total | |
global last_cpu_idle | |
f = open('/proc/stat', 'r') | |
cpu_line = f.readline() | |
f.close() | |
values = cpu_line.split()[1:-1] | |
total = 0L | |
for value in values: | |
total += long(value) | |
idle = long(values[3]) | |
result = 101 | |
total_delta = total - last_cpu_total | |
idle_delta = idle - last_cpu_idle | |
if last_cpu_total != 0 and total_delta >= 0: | |
if idle_delta == 0: | |
result = 0 | |
else: | |
result = int(100 * idle_delta / total_delta) | |
last_cpu_total = total | |
last_cpu_idle = idle | |
return 100 - result | |
def adjust(): | |
usage = get_cpu_usage() | |
if usage < 0: | |
return | |
global cnt_top | |
global slp | |
delta = usage - TARGET | |
if delta < 0: | |
delta = -delta | |
delta_per = float(delta) / TARGET | |
print ('usage: ' + str(usage) + ', cnt_top: ' + str(cnt_top) + ', slp: ' + str(slp) + ', delta_per: ' + str(delta_per)) | |
# cnt_incr | |
cnt_incr = int(delta_per * 500) | |
# cnt_decr | |
cnt_decr = int(delta_per * 500) | |
# slp_incr | |
slp_incr = 1 | |
# slp_decr | |
slp_decr = 1 | |
# ensures at least 1 | |
if cnt_incr < 0: | |
cnt_incr = 1 | |
if cnt_decr == 0: | |
cnt_decr = 1 | |
if slp_incr == 0: | |
slp_incr = 1 | |
if slp_decr == 0: | |
slp_decr = 1 | |
if usage > TARGET: | |
# cpu too high | |
# need to decrease cnt or increase slp | |
if cnt_top > (cnt_decr + CNT_MIN): | |
cnt_top -= cnt_decr | |
elif cnt_top > CNT_MIN: | |
cnt_top = CNT_MIN | |
elif slp + slp_incr < SLP_MAX: | |
slp += slp_incr | |
else: | |
slp = SLP_MAX | |
elif usage < TARGET: | |
# cpu too low | |
# need to increase cnt or decrease slp | |
if slp > (slp_decr + SLP_MIN): | |
slp -= slp_decr | |
elif slp > SLP_MIN: | |
slp = SLP_MIN | |
else: | |
cnt_top += cnt_incr | |
print ('update to: cnt_top: ' + str(cnt_top) + ', slp: ' + str(slp)) | |
TARGET = int(sys.argv[1]) | |
print ('the target cpu usage is ' + str(TARGET) + '%') | |
while True: | |
random.randint(1,101) | |
if cnt > cnt_top: | |
cnt = 0 | |
time.sleep(float(slp) / 1000) | |
if adjust_cnt > int(ADJUST_THRESHOLD / slp): | |
adjust_cnt = 0 | |
adjust() | |
adjust_cnt += 1 | |
cnt += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment