patternpythonMinor
Function for timing executions (inspired by MATLAB tic toc)
Viewed 0 times
matlabticfunctiontimingexecutionstocinspiredfor
Problem
Inspired by MATLAB's tic/toc I've written a short helper function for calculating execution time.
I'm well aware that there are python modules (e.g. timeit) that handle this kind of problem. However I do not want to time the execution of a whole script. I'm using this function in an interavtive shell for querying a mssql server.
What do you think? Is this good practice?
from time import time
def tic():
"""Simple helper function for timing executions.
Returns a closure that holds current time when calling tic().
Usage:
toc = tic()
//some code
print(toc())
"""
t = time()
return (lambda: (time() - t))I'm well aware that there are python modules (e.g. timeit) that handle this kind of problem. However I do not want to time the execution of a whole script. I'm using this function in an interavtive shell for querying a mssql server.
What do you think? Is this good practice?
Solution
I have a minor stylistic point, but you don't need (and shouldn't use) brackets around
It is minor but it actually confused me and made me think there was more of an expression there because of how rarely brackets are used like this.
return values. Neither the lambda itself nor the lambda's return value.return lambda: time() - tIt is minor but it actually confused me and made me think there was more of an expression there because of how rarely brackets are used like this.
Code Snippets
return lambda: time() - tContext
StackExchange Code Review Q#103873, answer score: 2
Revisions (0)
No revisions yet.