youzipi
youzipi

Reputation: 320

why the local function is faster in python and how to prove?

when i read the 500lines,it says that:

Putting it(methods) in a local saves us another small slice of time because locals are faster than builtins.

then i write a test like below:

import timeit

if __name__ == '__main__':
    _r = 5
    _n = 1000000
    s = str

    print(timeit.repeat("s(112)", setup="from __main__ import s", repeat=_r, number=_n))
    print(timeit.repeat("str(112)", repeat=_r, number=_n))

# 1.test s,then str
# [0.22136712074279785, 0.18772411346435547, 0.16153311729431152, 0.15581107139587402, 0.1546940803527832] s
# [0.19046807289123535, 0.1990509033203125, 0.19870710372924805, 0.18471217155456543, 0.1823439598083496] str

# 2. test str,then s
# [0.2088918685913086, 0.18737316131591797, 0.1878829002380371, 0.20372295379638672, 0.20828890800476074] str
# [0.15288996696472168, 0.158311128616333, 0.16825199127197266, 0.15237903594970703, 0.152756929397583] s

can anyone explain this? and why the first repeat of s cost more time? and how i can debug to the function call?

Upvotes: 1

Views: 74

Answers (1)

bird jesus
bird jesus

Reputation: 19

Did you read the previous paragraph?

The shortcut for str is also a micro-optimization. Names in Python can be local to a function, global to a module, or built-in to Python. Looking up a local name is faster than looking up a global or a built-in. We're used to the fact that str is a builtin that is always available, but Python still has to look up the name str each time it is used. Putting it in a local saves us another small slice of time because locals are faster than builtins.

Disclaimer: no claim to accuracy of claim.

Upvotes: 1

Related Questions