Skip to content

Instantly share code, notes, and snippets.

@zed
Created January 17, 2011 16:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zed/783011 to your computer and use it in GitHub Desktop.
Save zed/783011 to your computer and use it in GitHub Desktop.
What is faster x**.5 or math.sqrt(x) in Python?
.tox/
/MANIFEST
#!/usr/bin/env python
#http://stackoverflow.com/questions/327002/which-is-faster-in-python-x-5-or-math-sqrtx/327011#327011
import math
from timeit import default_timer as timer
try: xrange = xrange
except NameError:
xrange = range # py3k
def timeit1():
s = timer()
for i in xrange(750000):
z = i**.5
print("Took %f seconds" % (timer() - s))
def timeit2(arg=math.sqrt):
s = timer()
for i in xrange(750000):
z = arg(i)
print("Took %f seconds" % (timer() - s))
timeit1()
timeit2()
# Results produced on machine:
# $ uname -vms
# Linux #42-Ubuntu SMP Thu Dec 2 02:41:37 UTC 2010 x86_64
# $ cat /proc/cpuinfo | grep 'model name' | head -1
# model name : Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz
# | Interpreter | x**.5, | sqrt, | sqrt faster, % |
# | | seconds | seconds | |
# |----------------+---------+---------+----------------|
# | Python 3.2rc1+ | 0.32 | 0.27 | 19 |
# | Python 3.1.2 | 0.136 | 0.088 | 55 |
# | Python 3.0.1 | 0.155 | 0.102 | 52 |
# | Python 2.7 | 0.132 | 0.079 | 67 |
# | Python 2.6.6 | 0.121 | 0.075 | 61 |
# | PyPy 1.4.1 | 0.083 | 0.0159 | 422 |
# | Jython 2.5.1 | 0.132 | 0.22 | -40 |
# | Python 2.5.5 | 0.129 | 0.125 | 3 |
# | Python 2.4.6 | 0.131 | 0.123 | 7 |
##+TBLFM: $4=100*($2-$3)/$3;%.0f
# To reproduce results:
# * get source: [`git clone git://gist.github.com/783011.git gist-783011`][1]
# * install [`tox`][2]: `pip install tox`
# * run `tox` from the directory with `tox.ini` file.
# [1]: https://gist.github.com/783011
# [2]: http://codespeak.net/tox/
"""Dummy file to satisfy `tox`."""
from distutils.core import setup
NAME = 'dummy-package-for-tox'
VERSION = '0.0.1'
LICENSE = 'MIT'
AUTHOR = "me"
AUTHOR_EMAIL = "me@laptop"
setup(
name=NAME,
version=VERSION,
license=LICENSE,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=AUTHOR,
maintainer_email=AUTHOR_EMAIL,
)
[tox]
envlist = py32,py31,py30,py27,py26,pypy,jython,py25,py24
[testenv]
commands=
python -V
python claudiu.py
[testenv:pypy]
basepython=pypy
[testenv:jython]
commands=
jython -V
jython claudiu.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment