Skip to content

Instantly share code, notes, and snippets.

@directionless
Created August 14, 2014 02:09
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 directionless/0a9e14fccb63de021ae9 to your computer and use it in GitHub Desktop.
Save directionless/0a9e14fccb63de021ae9 to your computer and use it in GitHub Desktop.
Python WTF
#!/usr/bin/python
import random
import cProfile
import pstats
import math
from math import cos, sin, pi
def TESToverhead(a):
# This is just to check the call overhead
return ''
def TESTmath(a):
return math.cos(a)
def TESTdirect(a):
return cos(a)
def main():
for x in range(10000000):
a=random.randint(0,255)
TESToverhead(a)
TESTmath(a)
TESTdirect(a)
tmpfile = "/tmp/python.stats"
cProfile.run('main()', tmpfile)
p = pstats.Stats(tmpfile)
p.strip_dirs().sort_stats('time').print_stats("TEST")
# Running with pypy, this produces:
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 10000000 0.272 0.000 0.489 0.000 test_math_speed.py:13(TESTmath)
# 10000000 0.163 0.000 0.241 0.000 test_math_speed.py:16(TESTdirect)
# 10000000 0.078 0.000 0.078 0.000 test_math_speed.py:9(TESToverhead)
@johnpena
Copy link

In [11]: import dis

In [12]: dis.dis(TESTmath)
2 0 LOAD_GLOBAL 0 (math)
3 LOAD_ATTR 1 (cos)
6 LOAD_FAST 0 (a)
9 CALL_FUNCTION 1
12 RETURN_VALUE

In [13]: dis.dis(TESTdirect)
2 0 LOAD_GLOBAL 0 (cos)
3 LOAD_FAST 0 (a)
6 CALL_FUNCTION 1
9 RETURN_VALUE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment