Skip to content

Commit

Permalink
#941: implement cpu_freq() for Linux
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Dec 2, 2016
1 parent 6967c8d commit 8d83d5f
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
13 changes: 13 additions & 0 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1846,6 +1846,19 @@ def cpu_stats():
return _psplatform.cpu_stats()


if hasattr(_psplatform, "cpu_freq"):

def cpu_freq():
"""Return CPU frequencies as a list of nameduples including
current, min and max CPU frequency.
The CPUs order is supposed to be consistent with other CPU
functions having a 'percpu' argument and returning results for
multiple CPUs (cpu_times(), cpu_percent(), cpu_times_percent()).
Values are expressed in Mhz.
"""
return _psplatform.cpu_freq()


# =====================================================================
# --- system memory related functions
# =====================================================================
Expand Down
2 changes: 2 additions & 0 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ class NicDuplex(enum.IntEnum):
# psutil.cpu_stats()
scpustats = namedtuple(
'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'])
# psutil.cpu_freq()
scpufreq = namedtuple('scpufreq', ['curr', 'min', 'max'])

# --- for Process methods

Expand Down
35 changes: 35 additions & 0 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import base64
import errno
import functools
import glob
import os
import re
import socket
Expand Down Expand Up @@ -133,6 +134,8 @@ class IOPriority(enum.IntEnum):
"0B": _common.CONN_CLOSING
}

_DEFAULT = object()


# =====================================================================
# -- exceptions
Expand Down Expand Up @@ -276,6 +279,18 @@ def set_scputimes_ntuple(procfs_path):
return scputimes


def cat(fname, fallback=_DEFAULT, binary=True):
"""Return file content."""
try:
with open_binary(fname) if binary else open_text(fname) as f:
return f.read()
except IOError:
if fallback != _DEFAULT:
return fallback
else:
raise


try:
scputimes = set_scputimes_ntuple("/proc")
except Exception:
Expand Down Expand Up @@ -607,6 +622,26 @@ def cpu_stats():
ctx_switches, interrupts, soft_interrupts, syscalls)


if os.path.exists("/sys/devices/system/cpu/cpufreq"):

def cpu_freq():
# scaling_* files seem preferable to cpuinfo_*, see:
# http://unix.stackexchange.com/a/87537/168884
ret = []
ls = glob.glob("/sys/devices/system/cpu/cpufreq/policy[0-9]*")
# Sort the list so that '10' comes after '2'. This should
# ensure the CPU order is consistent with other CPU functions
# having a 'percpu' argument and returning results for multiple
# CPUs (cpu_times(), cpu_percent(), cpu_times_percent()).
ls.sort(key=lambda x: int(os.path.basename(x)[6:]))
for path in ls:
curr = int(cat(os.path.join(path, "scaling_cur_freq"))) / 1000
max_ = int(cat(os.path.join(path, "scaling_max_freq"))) / 1000
min_ = int(cat(os.path.join(path, "scaling_min_freq"))) / 1000
ret.append(_common.scpufreq(curr, min_, max_))
return ret


# =====================================================================
# --- network
# =====================================================================
Expand Down
10 changes: 10 additions & 0 deletions psutil/tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,16 @@ def test_cpu_stats(self):
if name in ('ctx_switches', 'interrupts'):
self.assertGreater(value, 0)

@unittest.skipUnless(hasattr(psutil, "cpu_freq"),
"platform not suported")
def test_cpu_freq(self):
ls = psutil.cpu_freq()
assert ls, ls
for nt in ls:
for name in nt._fields:
value = getattr(nt, name)
self.assertGreaterEqual(value, 0)

def test_os_constants(self):
names = ["POSIX", "WINDOWS", "LINUX", "OSX", "FREEBSD", "OPENBSD",
"NETBSD", "BSD", "SUNOS"]
Expand Down

0 comments on commit 8d83d5f

Please sign in to comment.