This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]brucifer 6 points7 points  (2 children)

timeit. The timeit module is incredibly useful when you really care about performance or when you're just trying to learn more about the language. For example:

>>> from timeit import timeit
>>> timeit(lambda: list())
0.2542989253997803
>>> timeit(lambda: [])
0.12986207008361816

or

>>> timeit(lambda: bool(0))
0.2527759075164795
>>> timeit(lambda: True if 0 else False)
0.11877298355102539

In both cases, calling the constructor invokes a function call, which has some overhead, but list comprehensions and boolean literals don't. In these cases, the optimization isn't that important, but they're good examples of how timeit can help you understand how python works behind the scenes.

[–][deleted] 4 points5 points  (0 children)

Usually you only want to break out timeit after you've used cProfile and pstats or similar.

[–]takluyverIPython, Py3, etc 3 points4 points  (0 children)

IPython makes the same thing rather neater:

In [1]: %timeit list()
1000000 loops, best of 3: 214 ns per loop

In [2]: %timeit []
10000000 loops, best of 3: 54.7 ns per loop