Skip to content

Commit 1a4acde

Browse files
committed
tools: use 1s idle cpu time to calculate cpu usage
procs_running is the value at the moment reading the value, which is too sensitive to short-time changes.
1 parent 09ae387 commit 1a4acde

File tree

2 files changed

+13
-11
lines changed

2 files changed

+13
-11
lines changed

lilac2/tools.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import os
77
import logging
88
from contextlib import suppress
9+
import time
910

1011
import tomllib
1112

@@ -30,18 +31,18 @@ def reap_zombies() -> None:
3031
while os.waitid(os.P_ALL, 0, os.WEXITED | os.WNOHANG) is not None:
3132
pass
3233

33-
def get_running_task_cpu_ratio() -> float:
34-
ncpu = os.process_cpu_count()
35-
running = 0
34+
def get_cpu_idle() -> tuple[int, int]:
3635
with open('/proc/stat') as f:
37-
for l in f:
38-
if l.startswith('procs_running '):
39-
running = int(l.split()[1])
40-
break
41-
if ncpu and running:
42-
return running / ncpu
43-
else:
44-
return 0.0
36+
line = f.readline()
37+
numbers = [int(x) for x in line.split()[1:]]
38+
return numbers[3], sum(numbers)
39+
40+
def get_running_task_cpu_ratio() -> float:
41+
a = get_cpu_idle()
42+
time.sleep(1)
43+
b = get_cpu_idle()
44+
idle = (b[0] - a[0]) / (b[1] - a[1])
45+
return 1 - idle
4546

4647
def get_avail_memory() -> int:
4748
with open('/proc/meminfo') as f:

lilac2/workerman.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ def try_accept_package(
4949
cpu_ratio, memory_avail = self.get_resource_usage()
5050

5151
if cpu_ratio > 1.0 and self.current_task_count > 0:
52+
logger.debug('[%s] high CPU usage (%.2f), idling', self.name, cpu_ratio)
5253
return []
5354

5455
def sort_key(pkg):

0 commit comments

Comments
 (0)