I tested the codes below with time function of bash.
# test_local.py
def main():
n = 10 ** 7
mod = 10 ** 9 + 7
x = 0
for i in range(n):
x += i
x %= mod
if __name__ == "__main__":
main()
# test_global.py
n = 10 ** 7
mod = 10 ** 9 + 7
x = 0
for i in range(n):
x += i
x %= mod
Results:
python3 test_local.py 1.03s user 0.02s system 91% cpu 1.139 total
python3 test_global.py 1.92s user 0.01s system 98% cpu 1.956 total
pypy3 test_local.py 0.26s user 0.12s system 36% cpu 1.034 total
pypy3 test_global.py 0.13s user 0.03s system 97% cpu 0.161 total
Env:
CPython3 (3.8.2), PyPy3 (7.3.0)
Why is test_local.py slower than test_global.py in PyPy3, although the result is the opposite in CPython?
Update
Following the answer by Armin Rigo, I tried another code below.
It works faster while being kept most parts in main().
# test_global_constant.py
MOD = 10 ** 9 + 7
def main():
n = 10 ** 7
x = 0
for i in range(n):
x += i
x %= MOD
if __name__ == "__main__":
main()
Results:
python3 test_global_constant.py 1.08s user 0.01s system 99% cpu 1.099 total
pypy3 test_global_constant.py 0.12s user 0.03s system 95% cpu 0.164 total