Skip to content

Instantly share code, notes, and snippets.

@jdowner
Last active August 29, 2015 14:06
Show Gist options
  • Save jdowner/38740a808975bf6d9518 to your computer and use it in GitHub Desktop.
Save jdowner/38740a808975bf6d9518 to your computer and use it in GitHub Desktop.
Performance testing numpy subtract verses the interpreter
#!/usr/bin/python
import contextlib
import numpy
import time
@contextlib.contextmanager
def timer():
start = time.time()
yield
finish = time.time()
print('elapsed time: {}'.format(finish - start))
def using_interpreter():
with timer():
for _ in range(1000):
mat = numpy.random.random((100,100))
for row in mat:
row -= numpy.min(row)
def using_numpy():
with timer():
for _ in range(1000):
mat = numpy.random.random((100,100))
mat = numpy.subtract(mat, numpy.min(mat, axis=1)[:,numpy.newaxis])
def main():
using_interpreter()
using_numpy()
if __name__ == "__main__":
main()
@jdowner
Copy link
Author

jdowner commented Sep 21, 2014

The results that I get on my machine are,

jdowner@erebor:munkres-subtraction$ python munkres-np-subtract.py 
elapsed time: 0.401839971542
elapsed time: 0.119607925415

So using numpy is about 4 times faster that going through the interpreter.

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