Skip to content

Instantly share code, notes, and snippets.

@13steinj
Created February 6, 2018 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 13steinj/a1c288295aa2716f4e8d868f07505941 to your computer and use it in GitHub Desktop.
Save 13steinj/a1c288295aa2716f4e8d868f07505941 to your computer and use it in GitHub Desktop.
How in the world does this occur?
>>> import timeit, dis
>>> t1 = timeit.Timer("""def foo(): return pprint.pprint([])""", setup="import pprint")
>>> t2 = timeit.Timer("""def foo(): import pprint; return pprint.pprint([])""")
>>> t1.repeat()
[0.1467437744140625, 0.12576889991760254, 0.12010502815246582]
>>> t2.repeat()
[0.08302998542785645, 0.07528400421142578, 0.07703089714050293]
>>> def foo(): return pprint.pprint([])
>>> def foo2(): import pprint; return pprint.pprint([])
>>> dis.dis(foo)
1 0 LOAD_GLOBAL 0 (pprint)
3 LOAD_ATTR 0 (pprint)
6 BUILD_LIST 0
9 CALL_FUNCTION 1
12 RETURN_VALUE
>>> dis.dis(foo)
1 0 LOAD_CONST 1 (-1)
3 LOAD_CONST 0 (None)
6 IMPORT_NAME 0 (pprint)
9 STORE_FAST 0 (pprint)
12 LOAD_FAST 0 (pprint)
15 LOAD_ATTR 0 (pprint)
18 BUILD_LIST 0
21 CALL_FUNCTION 1
24 RETURN_VALUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment