From db2589e5eb1671e6464f2172b846478aa61eb8ef Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Sun, 1 May 2016 02:32:29 +0200 Subject: [PATCH] [Linux] speedup Process.pid() by 20% by reading it from /proc/pid/stat instead of /proc/pid/status --- HISTORY.rst | 2 ++ psutil/_pslinux.py | 14 +++++--------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 2d15bd7f0..e1c8a75b2 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -8,6 +8,8 @@ Bug tracker at https://github.com/giampaolo/psutil/issues - #795: [Windows] new APIs to deal with Windows services: win_service_iter() and win_service_get(). - #800: [Linux] psutil.virtual_memory() returns a new "shared" memory field. +- XXX: [Linux] speedup /proc parsing: + - Process.ppid() is 20% faster **Bug fixes** diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 93e91a68e..6b9dd6d07 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -1395,15 +1395,11 @@ def num_fds(self): @wrap_exceptions def ppid(self): - fpath = "%s/%s/status" % (self._procfs_path, self.pid) - with open_binary(fpath) as f: - for line in f: - if line.startswith(b"PPid:"): - # PPid: nnnn - ppid = int(line.split()[1]) - self._ppid = ppid - return ppid - raise NotImplementedError("line 'PPid' not found in %s" % fpath) + with open_binary("%s/%s/stat" % (self._procfs_path, self.pid)) as f: + data = f.read() + # ignore the first two values ("pid (exe)") + data = data[data.rfind(b')') + 2:] + return int(data.split(b' ')[1]) @wrap_exceptions def uids(self):