Skip to content

Commit

Permalink
Linux, cpu_freq(): diminish os.stat() calls a bit
Browse files Browse the repository at this point in the history
Micro optimization in reference to #1852 and #1851.
Use glob.glob(), which internally relies on os.scandir()
in order to list /sys/devices/system/cpu/cpufreq files.
In doing so, we avoid os.path.exists() for each CPU, which
internally uses os.stat().

Signed-off-by: Giampaolo Rodola <g.rodola@gmail.com>
  • Loading branch information
giampaolo committed Dec 29, 2020
1 parent 1188d8e commit f18438d
Showing 1 changed file with 5 additions and 12 deletions.
17 changes: 5 additions & 12 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,19 +726,12 @@ def cpu_freq():
Contrarily to other OSes, Linux updates these values in
real-time.
"""
def get_path(num):
for p in ("/sys/devices/system/cpu/cpufreq/policy%s" % num,
"/sys/devices/system/cpu/cpu%s/cpufreq" % num):
if os.path.exists(p):
return p

paths = sorted(
glob.glob("/sys/devices/system/cpu/cpufreq/policy[0-9]*") or
glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq"))
ret = []
for n in range(cpu_count_logical()):
path = get_path(n)
if not path:
continue

pjoin = os.path.join
pjoin = os.path.join
for path in paths:
curr = cat(pjoin(path, "scaling_cur_freq"), fallback=None)
if curr is None:
# Likely an old RedHat, see:
Expand Down

0 comments on commit f18438d

Please sign in to comment.