Most advice I can find on how to tell how long a chunk of my code is taking falls into one of a few camps:
- Use timeit
- Grab a timestamp before and after the code in question runs and take the difference of the two. The timestamp may come from time.time, time.clock, timeit.default_timer, or time.perf_counter (see discussion here). I'm particularly enamored of this solution which uses a decorator.
- Use a profiler
My understanding is that #2 and #1 (which are the same under the hood) tell me how much wall clock time has elapsed, which can include other processes in addition to my code. For example, the documentation for time.perf_counter says, "It does include time elapsed during sleep and is system-wide."
So I'm left with a profiler. I'd prefer not to use a profiler for two reasons: first, it slows my code down, and second, thus far I haven't found a nice way to invoke it. I'd rather use something like the @timeit
decorator than pass a string suitable for use with exec
.
Can I get a measurement that's free of background stuff without going so far as to use a profiler?