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

Why is if True slower than if 1?

True and False are not keywords in Python 2. They must resolve at runtime. This has been changed in Python 3 Same test on Python 3: >>> timeit.timeit(‘test1()’,setup=”from __main__ import test1″, number=10000000) 2.806439919999889 >>> timeit.timeit(‘test2()’,setup=”from __main__ import test2″, number=10000000) 2.801301520000038 >>> timeit.timeit(‘test3()’,setup=”from __main__ import test3″, number=10000000) 2.7952816800000164 >>> timeit.timeit(‘test4()’,setup=”from __main__ import test4″, number=10000000) 2.7862537199999906 Time … Read more

How can I capture return value with Python timeit module?

For Python 3.5 you can override the value of timeit.template timeit.template = “”” def inner(_it, _timer{init}): {setup} _t0 = _timer() for _i in _it: retval = {stmt} _t1 = _timer() return _t1 – _t0, retval “”” unutbu’s answer works for python 3.4 but not 3.5 as the _template_func function appears to have been removed in … Read more

accurately measure time python function takes

According to the Python documentation, it has to do with the accuracy of the time function in different operating systems: The default timer function is platform dependent. On Windows, time.clock() has microsecond granularity but time.time()‘s granularity is 1/60th of a second; on Unix, time.clock() has 1/100th of a second granularity and time.time() is much more … Read more

timeit and its default_timer completely disagree

As Martijn commented, the difference is Python’s garbage collection, which timeit.timeit disables during its run. And zip creates 10 million iterator objects, one for each of the 10 million iterables it’s given. So, garbage-collecting 10 million objects simply takes a lot of time, right? Mystery solved! Well… no. That’s not really what happens, and it’s … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)