Last active
December 16, 2015 23:19
-
-
Save johshoff/5513562 to your computer and use it in GitHub Desktop.
nap — better than sleep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from sys import argv, exit | |
from time import sleep, time | |
import re | |
if len(argv) != 2: | |
print('Usage: nap <interval>') | |
print('Where: <interval> is <num>h hours') | |
print(' <num>m minutes') | |
print(' <num>s seconds') | |
print(' <num>ms milliseconds') | |
print(' <num> is a floating point number') | |
exit(-1) | |
num, unit = re.match('^(\d+\.?\d*)(\w+)$', argv[1]).groups() | |
seconds_in_unit = { | |
'h' : 60 * 60, | |
'm' : 60, | |
's' : 1, | |
'ms': 0.001, | |
} | |
seconds = seconds_in_unit[unit] * float(num) | |
try: | |
import psutil, os | |
start_time = psutil.Process(os.getpid()).create_time | |
except e: | |
print 'Install psutil for better precision' | |
start_time = time() | |
bias = 0.0065 # takes some amount of extra milliseconds to get here. Based on unscientific experiments | |
sleep(max(seconds - (time() - start_time) - bias, 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment