Skip to content

Instantly share code, notes, and snippets.

@vindolin
Last active August 29, 2015 14:06
Show Gist options
  • Save vindolin/3b128838fb5431fa505d to your computer and use it in GitHub Desktop.
Save vindolin/3b128838fb5431fa505d to your computer and use it in GitHub Desktop.
Simple module for rought timing of python code
from __future__ import print_function
import time
print_func = print
def format_sec(milliseconds):
return '{:>8.3f} sec.'.format(milliseconds / 1000.0)
current_milli_time = lambda: int(round(time.time() * 1000))
script_starttime = current_milli_time()
last_starttime = current_milli_time()
last_label = None
history = {}
def timeit(label):
current_time = current_milli_time()
global last_starttime, last_label
if last_starttime:
timediff = current_time - last_starttime
history[label] = current_time
since_label_result = ''
if '>' in label:
from_label, label = label.split('>')
if from_label in history:
since_label_time_diff = current_time - history[from_label]
since_label_result = '\033[38;5;202m{}\033[0;00m since \033[38;5;200m[{}]\033[0;00m'.format(format_sec(since_label_time_diff), from_label)
result = '\033[38;5;200m{:<16}\033[0;00m step: \033[38;5;214m{}\033[0;00m total: \033[38;5;230m{}\033[0;00m {}'.format('[{}]'.format(label), format_sec(timediff), format_sec(current_time - script_starttime), since_label_result)
print_func(result)
last_starttime = None
last_label = None
if label:
last_label = label
last_starttime = current_time
import atexit
atexit.register(lambda: timeit('ATEXIT'))
if __name__ == '__main__':
from time import sleep
timeit('init')
sleep(1)
timeit('loading data')
sleep(1.2)
timeit('parsing data')
sleep(1)
timeit('loading data>data complete')
sleep(0.5)
timeit('end')
sleep(0.1)
@vindolin
Copy link
Author

will output this (colored in RL):

[init]           step:    0.006 sec. total:    0.006 sec. 
[loading data]   step:    1.001 sec. total:    1.007 sec. 
[parsing data]   step:    1.202 sec. total:    2.209 sec. 
[data complete]  step:    1.001 sec. total:    3.210 sec.    2.203 sec. since [loading data]
[end]            step:    0.501 sec. total:    3.711 sec. 
[ATEXIT]         step:    0.100 sec. total:    3.811 sec. 

This is how it looks with colors: https://i.imgur.com/k1S0fPC.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment