Surprising results with Python timeit: Counter() vs defaultdict() vs dict()

Yes, this is expected; the Counter() constructor uses Counter.update() which uses self.get() to load initial values rather than rely on __missing__. Moreover, the defaultdict __missing__ factory is handled entirely in C code, especially when using another type like int() that is itself implemented in C. The Counter source is pure Python and as such the … Read more

What is %timeit in Python?

%timeit is an IPython magic function, which can be used to time a particular piece of code (a single execution statement, or a single method). From the documentation: %timeit Time execution of a Python statement or expression Usage, in line mode: %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement To use it, for example if … Read more

How do I measure elapsed time in Python?

Use time.time() to measure the elapsed wall-clock time between two points: import time start = time.time() print(“hello”) end = time.time() print(end – start) This gives the execution time in seconds. Another option since Python 3.3 might be to use perf_counter or process_time, depending on your requirements. Before 3.3 it was recommended to use time.clock (thanks … Read more

timeit versus timing decorator

Use wrapping from functools to improve Matt Alcock’s answer. from functools import wraps from time import time def timing(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) te = time() print ‘func:%r args:[%r, %r] took: %2.4f sec’ % \ (f.__name__, args, kw, te-ts) return result return wrap In an example: @timing def … Read more

List comprehension vs generator expression’s weird timeit results?

Expanding on Paulo‘s answer, generator expressions are often slower than list comprehensions because of the overhead of function calls. In this case, the short-circuiting behavior of in offsets that slowness if the item is found fairly early, but otherwise, the pattern holds. I ran a simple script through the profiler for a more detailed analysis. … Read more

How to use timeit module

If you want to use timeit in an interactive Python session, there are two convenient options: Use the IPython shell. It features the convenient %timeit special function: In [1]: def f(x): …: return x*x …: In [2]: %timeit for x in range(100): f(x) 100000 loops, best of 3: 20.3 us per loop In a standard … Read more