Last active
October 15, 2017 15:08
-
-
Save Endogen/e7a88233e61d326ffaa73d708e3fbccc to your computer and use it in GitHub Desktop.
Get the execution time of a python script
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
#python3 | |
# Source: https://stackoverflow.com/questions/1557571/how-do-i-get-time-of-a-python-programs-execution/12344609#12344609 | |
import atexit | |
from time import time | |
from datetime import timedelta | |
def secondsToStr(t): | |
return str(timedelta(seconds=t)) | |
line = "="*40 | |
def log(s, elapsed=None): | |
print(line) | |
print(secondsToStr(time()), '-', s) | |
if elapsed: | |
print("Elapsed time:", elapsed) | |
print(line) | |
print() | |
def endlog(): | |
end = time() | |
elapsed = end-start | |
log("End Program", secondsToStr(elapsed)) | |
def now(): | |
return secondsToStr(time()) | |
start = time() | |
atexit.register(endlog) | |
log("Start Program") |
Another method to do this - but not so pythonic - is this:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's possible to call
timing.log
from within the program if there are significant stages within the program we want to show. But just includingimport timing
will print the start and end times, and overall elapsed time. The functionsecondsToStr
just formats a floating point number of seconds to hh:mm:ss.sss form.