Skip to content

Instantly share code, notes, and snippets.

@jkloth
Last active March 31, 2022 17:01
Show Gist options
  • Select an option

  • Save jkloth/d5ab8540e5e47d29990321548e79c59e to your computer and use it in GitHub Desktop.

Select an option

Save jkloth/d5ab8540e5e47d29990321548e79c59e to your computer and use it in GitHub Desktop.
Simple script to measure different function calling styles
class Test:
def f1(self, a, b, reps):
def cmp(a, b):
return
for i in range(reps):
cmp(a, b)
def _f2(self, a, b):
return
def f2(self, a, b, reps):
for i in range(reps):
self._f2(a, b)
def format_time(dt):
units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0}
scales = [(scale, unit) for unit, scale in units.items()]
scales.sort(reverse=True)
for scale, unit in scales:
if dt >= scale:
break
return "%.3g %s" % (dt / scale, unit)
import time
timer = time.perf_counter
test = Test()
# Show when inner functions become faster than methods
t1 = t2 = 0
reps = 100
while t2 <= t1:
start = timer()
test.f1(1,2, reps)
t1 = timer() - start
start = timer()
test.f2(1,2, reps)
t2 = timer() - start
print(reps, '-> inner:', format_time(t1), 'method:', format_time(t2))
reps += 100
max_reps = reps
# Show timings
stats = {
# TestCase class -> (assertASTEqual, compares)
'CosmeticTestCase': (16, 232),
'DirectoryTestCase': (685, 2951999),
'UnparseTestCase': (841, 2953878),
}
for name, (calls, compares) in stats.items():
reps = min(compares // calls, max_reps)
print(f'{name} ({reps} compares)')
start = timer()
for i in range(calls):
test.f1(1,2, reps)
t1 = timer() - start
print(' inner:', format_time(t1))
start = timer()
for i in range(calls):
test.f2(1,2, reps)
t2 = timer() - start
print(' method:', format_time(t2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment