Getting “global name ‘foo’ is not defined” with Python’s timeit

Change this line: t = timeit.Timer(“foo()”) To this: t = timeit.Timer(“foo()”, “from __main__ import foo”) Check out the link you provided at the very bottom. To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement: I just tested it on my machine and it … Read more

Why is it slower to iterate over a small string than a small list?

TL;DR The actual speed difference is closer to 70% (or more) once a lot of the overhead is removed, for Python 2. Object creation is not at fault. Neither method creates a new object, as one-character strings are cached. The difference is unobvious, but is likely created from a greater number of checks on string … 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 can I time a code segment for testing performance with Pythons timeit?

You can use time.time() or time.clock() before and after the block you want to time. import time t0 = time.time() code_block t1 = time.time() total = t1-t0 This method is not as exact as timeit (it does not average several runs) but it is straightforward. time.time() (in Windows and Linux) and time.clock() (in Linux) are … 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

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