# Function for timing executions (inspired by MATLAB tic toc)

Inspired by MATLAB's tic/toc I've written a short helper function for calculating execution time.

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?

I have a minor stylistic point, but you don't need (and shouldn't use) brackets around return values. Neither the lambda itself nor the lambda's return value.

return lambda: time() - t


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.

timeit can time arbitrary expressions, so I don't see a good use case for what you're doing here. In fact, it could be considered bad practice in the sense that timing information, which is normally in the same category as debugging code, shouldn't be built into your program or function or whatever. You should be able to add that on "outside", only if needed. That's what timeit allows you to do.

Of course, sometimes it is actually useful to include timing information as part of your program. Even in that case, it seems like overkill to use a lambda function. A simpler way would be

def main_timed():
start = time()
main()
print time() - start


But I don't see any major disadvantage to the way you're doing it. It's just that other programmers will probably find it kind of odd.

• Thanks for taking the time to review and provide feedback. However, the timing information is not for debugging. The program provides an interactive shell for querying a database. Timing info is used for "fetched data in x seconds.". The timing code is needed in several places in the code. I find my solution more elegant than the one in your code snippet. – Idefux Sep 5 '15 at 18:11
• @Idefux that's exactly why I included the second paragraph, about what to do if your timing information is not just for debugging. I find your code in the question distinctly less elegant than the one in my code snippet, and if you don't agree, I don't suppose there is anything more I can tell you. – David Z Sep 5 '15 at 18:38