Skip to content

Instantly share code, notes, and snippets.

@NoahTheDuke
Last active November 5, 2016 18:14
Show Gist options
  • Save NoahTheDuke/051f90751e34a4e10df6a52794004da8 to your computer and use it in GitHub Desktop.
Save NoahTheDuke/051f90751e34a4e10df6a52794004da8 to your computer and use it in GitHub Desktop.
In [27]: %%timeit
...: result = []
...: for i in range(2000):
...: result.append(i * 2)
...:
1000 loops, best of 3: 285 µs per loop
In [28]: %%timeit
...: result = []
...: add = result.append
...: for i in range(2000):
...: add(i * 2)
...:
1000 loops, best of 3: 211 µs per loop
In [29]: %timeit result = [i * 2 for i in range(2000)]
10000 loops, best of 3: 183 µs per loop
In [16]: import dis
...: import inspect
...: import timeit
...:
...:
...: programs = dict(
...: loop="""
...: result = []
...: for i in range(20):
...: result.append(i * 2)
...: """,
...: loop_faster="""
...: result = []
...: add = result.append
...: for i in range(20):
...: add(i * 2)
...: """,
...: comprehension='result = [i * 2 for i in range(20)]',
...: )
...:
...:
...: for name, text in programs.items():
...: print(name, timeit.Timer(stmt=text).timeit())
...: code = compile(text, '<string>', 'exec')
...: dis.disassemble(code)
...:
loop 3.253456643191271
2 0 BUILD_LIST 0
3 STORE_NAME 0 (result)
3 6 SETUP_LOOP 37 (to 46)
9 LOAD_NAME 1 (range)
12 LOAD_CONST 0 (20)
15 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
18 GET_ITER
>> 19 FOR_ITER 23 (to 45)
22 STORE_NAME 2 (i)
4 25 LOAD_NAME 0 (result)
28 LOAD_ATTR 3 (append)
31 LOAD_NAME 2 (i)
34 LOAD_CONST 1 (2)
37 BINARY_MULTIPLY
38 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
41 POP_TOP
42 JUMP_ABSOLUTE 19
>> 45 POP_BLOCK
>> 46 LOAD_CONST 2 (None)
49 RETURN_VALUE
loop_faster 2.745425177352331
2 0 BUILD_LIST 0
3 STORE_NAME 0 (result)
3 6 LOAD_NAME 0 (result)
9 LOAD_ATTR 1 (append)
12 STORE_NAME 2 (add)
4 15 SETUP_LOOP 34 (to 52)
18 LOAD_NAME 3 (range)
21 LOAD_CONST 0 (20)
24 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
27 GET_ITER
>> 28 FOR_ITER 20 (to 51)
31 STORE_NAME 4 (i)
5 34 LOAD_NAME 2 (add)
37 LOAD_NAME 4 (i)
40 LOAD_CONST 1 (2)
43 BINARY_MULTIPLY
44 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
47 POP_TOP
48 JUMP_ABSOLUTE 28
>> 51 POP_BLOCK
>> 52 LOAD_CONST 2 (None)
55 RETURN_VALUE
comprehension 2.4492211362247645
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x0000000006AC84B0, file "<string>", line 1>)
3 LOAD_CONST 1 ('<listcomp>')
6 MAKE_FUNCTION 0
9 LOAD_NAME 0 (range)
12 LOAD_CONST 2 (20)
15 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
18 GET_ITER
19 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
22 STORE_NAME 1 (result)
25 LOAD_CONST 3 (None)
28 RETURN_VALUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment