Skip to content

Commit

Permalink
#1007 / boot_time() / win: consider 1 sec fluctuation between calls a…
Browse files Browse the repository at this point in the history
…cceptable and return always the same value
  • Loading branch information
giampaolo committed May 8, 2017
1 parent 3e06eee commit 49ce1f6
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
3 changes: 3 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

**Bug fixes**

- 1007_: [Windows] boot_time() can have a 1 sec fluctuation between calls; the
value of the first call is now cached so that boot_time() always returns the
same value if fluctuation is <= 1 second.
- 1014_: [Linux] Process class can mask legitimate ENOENT exceptions as
NoSuchProcess.
- 1016_: disk_io_counters() raises RuntimeError on a system with no disks.
Expand Down
14 changes: 13 additions & 1 deletion psutil/_pswindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,9 +401,21 @@ def sensors_battery():
# =====================================================================


_last_btime = 0


def boot_time():
"""The system boot time expressed in seconds since the epoch."""
return cext.boot_time()
# This dirty hack is to adjust the precision of the returned
# value which may have a 1 second fluctuation, see:
# https://github.com/giampaolo/psutil/issues/1007
global _last_btime
ret = cext.boot_time()
if abs(ret - _last_btime) <= 1:
return _last_btime
else:
_last_btime = ret
return ret


def users():
Expand Down
11 changes: 11 additions & 0 deletions psutil/tests/test_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

"""Windows specific tests."""

import datetime
import errno
import glob
import os
Expand Down Expand Up @@ -179,6 +180,16 @@ def test_net_if_stats(self):
self.assertTrue(ps_names & wmi_names,
"no common entries in %s, %s" % (ps_names, wmi_names))

def test_boot_time(self):
wmi_os = wmi.WMI().Win32_OperatingSystem()
wmi_btime_str = wmi_os[0].LastBootUpTime.split('.')[0]
wmi_btime_dt = datetime.datetime.strptime(
wmi_btime_str, "%Y%m%d%H%M%S")
psutil_dt = datetime.datetime.fromtimestamp(psutil.boot_time())
diff = abs((wmi_btime_dt - psutil_dt).total_seconds())
# Wmic time is 2 secs lower for some reason; that's OK.
self.assertLessEqual(diff, 2)


# ===================================================================
# sensors_battery()
Expand Down

0 comments on commit 49ce1f6

Please sign in to comment.