Skip to content

Instantly share code, notes, and snippets.

@kbfreder
Last active February 14, 2020 20:17
Show Gist options
  • Save kbfreder/28e34e53fcd90c268e0c04d4bb02d81e to your computer and use it in GitHub Desktop.
Save kbfreder/28e34e53fcd90c268e0c04d4bb02d81e to your computer and use it in GitHub Desktop.
time how long your code takes to run
# BASIC
# ----------------------------------------------------------------------
# elapsed time
import time
start_time = time.time()
'''code to execute'''
end_time = time.time()
print('Elapsed time: {:.1f} min'.format((end_time - start_time) / 60))
# print start time
import datetime as dt
from pytz import timezone
TIMEZONE = 'US/Mountain' # change to your timezone
tz = timezone(TIMEZONE)
start_time = dt.datetime.now(tz)
print(f"Started at: {start_time.strftime('%Y-%m-%d %H:%M')} local time")
'''code to execute'''
end_time = dt.datetime.now(tz)
print(f'Elapsed time: {(end_time - start_time) / dt.timedelta(seconds=60):.1f} minutes')
# PROGRESS
# ----------------------------------------------------------------------
import sys
import time # only needed for demo
qperc = 0 # placeholder for percent of progress
qincr = 10 # how often (%) to print out progress report
i = 0 # counter variable, for demo
stop = 10 # for demo
while i < stop: # replace with code that indicates task not finished,
# ex: not jobs.empty():
sys.stdout.write('.')
sys.stdout.flush()
# qcurr is some measure of progress, e.g.:
# qcurr = 100 * (len(data) - jobs.qsize()) / len(data)
# for this demo, we just set equal to our counter / stop
qcurr = 100 * (i / stop)
# print out progress every qincr
if qcurr - qincr >= qperc:
qperc = qcurr
sys.stdout.write('%u%%' % qperc)
sys.stdout.flush()
time.sleep(1) # for demo
i += 1 # for demo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment