timeit

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

眉间皱痕 提交于 2019-11-26 09:19:00
问题 I\'m trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called timeit that purports to do exactly that: import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer(\"foo()\") time = t.timeit(1) print \"took %fs\\n\" % (time,) dotime() However, this produces an error: Traceback (most recent call last): File \"<stdin>\", line 1, in <module> File \"<stdin>\", line 3,

List comprehension vs generator expression&#39;s weird timeit results?

谁说胖子不能爱 提交于 2019-11-26 01:32:02
I was answering this question , I preferred generator expression here and used this, which I thought would be faster as generator doesn't need to create the whole list first: >>> lis=[['a','b','c'],['d','e','f']] >>> 'd' in (y for x in lis for y in x) True And Levon used list comprehension in his solution , >>> lis = [['a','b','c'],['d','e','f']] >>> 'd' in [j for i in mylist for j in i] True But when I did the timeit results for these LC was faster than generator: ~$ python -m timeit -s "lis=[['a','b','c'],['d','e','f']]" "'d' in (y for x in lis for y in x)" 100000 loops, best of 3: 2.36 usec

List comprehension vs generator expression&#39;s weird timeit results?

不羁的心 提交于 2019-11-26 01:07:54
问题 I was answering this question, I preferred generator expression here and used this, which I thought would be faster as generator doesn\'t need to create the whole list first: >>> lis=[[\'a\',\'b\',\'c\'],[\'d\',\'e\',\'f\']] >>> \'d\' in (y for x in lis for y in x) True And Levon used list comprehension in his solution, >>> lis = [[\'a\',\'b\',\'c\'],[\'d\',\'e\',\'f\']] >>> \'d\' in [j for i in mylist for j in i] True But when I did the timeit results for these LC was faster than generator:

Measure time elapsed in Python

余生颓废 提交于 2019-11-25 22:26:36
问题 What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I\'m using the timeit module wrong, but the docs are just confusing for me. import timeit start = timeit.timeit() print(\"hello\") end = timeit.timeit() print(end - start) 回答1: If you just want to measure the elapsed wall-clock time between two points, you could use time.time(): import time start = time.time() print("hello") end = time.time()