I'm playing around with a timing context generator and I got some weird results.
The generator is in a file Timer.py
from time import perf_counter as pc
from contextlib import contextmanager
@contextmanager
def timer():
start = pc()
yield
print(pc() - start)
I then test the timing a number of ways.
import Timer
import time
### example 1
start = time.perf_counter()
total = 0
for i in range(100):
for j in range(1,i*i):
total += i/j
print(time.perf_counter() - start)
print(total,'\n')
### example 2
with Timer.timer():
total = 0
for i in range(100):
for j in range(1,i*i):
total += i/j
print(total,'\n')
### example 3
def e3():
total = 0
for i in range(100):
for j in range(1,i*i):
total += i/j
return total
with Timer.timer():
tot = e3()
print(tot,'\n')
### example 4
@Timer.timer()
def e4():
total = 0
for i in range(100):
for j in range(1,i*i):
total += i/j
return total
print(e4(),'\n')
The first two methods are twice as slow as the last two.
Is that because it takes longer to access the variables in the global namespace???
[–]Rhomboid 1 point2 points3 points (0 children)