自動Suspend CPU佔用率最高程序,夏天CPU好幫手
阿新 • • 發佈:2019-02-13
內容如程式碼所示,溫度和suspend、resume策略你需要自己修改一下:
#!/usr/bin/env python # -*- coding=utf-8 -*- import commands, signal, time, os, re alarm_temp = 90 safe_temp = 70 ignore_cpu_percent = 10.0 pid_pool = [] my_name = "" def resume_one(): global pid_pool if len(pid_pool) == 0: return pid = pid_pool[0] os.kill(pid, signal.SIGCONT) print "Resumed ", pid, " at ", time.strftime('%X %x %Z') pid_pool.remove(pid) def suspend_one(): global pid_pool, myname statue, output = commands.getstatusoutput('ps -eo "%C;%p;%u"') p = re.compile("([0-9\.]+); *?([0-9\.]+);(.*)") m = p.findall(output) if len(m) == 0: return m.sort(lambda a,b: -cmp(float(a[0]),float(b[0]))) for item in m: cpu = float(item[0]) pid = int(item[1]) user = item[2] if user != my_name: continue if cpu <= ignore_cpu_percent: return if pid in pid_pool: continue os.kill(pid, signal.SIGSTOP) print "Suspended", pid, " at ", time.strftime('%X %x %Z') pid_pool.append(pid) time.sleep(10) return def resume_all(): global pid_pool for pid in pid_pool: os.kill(pid, signal.SIGCONT) print "Resumed", pid, " at ", time.strftime('%X %x %Z') pid_pool = [] def sigint_handler(signum = 0, e = 0): resume_all() exit(1) def get_temp(): statue, output = commands.getstatusoutput("sensors") p = re.compile("temp1:.*?\+(.*?)°C") m = p.findall(output) if len(m) > 0: return float(m[0]) else: return 0 def get_my_name(): global my_name statue, output = commands.getstatusoutput("whoami") my_name = output if __name__ == '__main__': get_my_name() signal.signal(signal.SIGINT, sigint_handler) while True: temp = get_temp() if temp >= alarm_temp: suspend_one() elif temp <= safe_temp: resume_one() time.sleep(1)