Advertisement
keith_h

timeit example

Mar 31st, 2011
1,053
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3. import sys
  4. import timeit
  5.  
  6. def main():
  7.     test(2000000, "range")
  8.     test(2000000, "xrange")
  9.     test(2000000, "numpy.arange", "import numpy")
  10.    
  11.     test2(2000000)
  12.     test3(2000000)
  13.  
  14. def test(n, fxn, setup='pass'):
  15.     s = """\
  16.    nrepArray = %s(%d)
  17.    for i in %s(%d):
  18.        pass
  19.    """ % (fxn, n, fxn, n)
  20.     t = timeit.Timer(stmt=s, setup=setup)
  21.     time  = t.timeit(number=1)
  22.     print "%s took %f seconds (n=%d)" % (fxn, time, n)
  23.    
  24. def test2(n):
  25.     s = """[x * 2 for x in xrange(%d)]""" % n
  26.     t = timeit.Timer(stmt=s)
  27.     time = t.timeit(number=1)
  28.     print "scale multiplication (xrange) took %f seconds (n=%d)" % (time, n)
  29.  
  30. def test3(n):
  31.     s = """numpy.arange(%d) * 2""" % n
  32.     t = timeit.Timer(stmt=s, setup="import numpy")
  33.     time = t.timeit(number=1)
  34.     print "scale multiplication (numpy.arange) took %f seconds (n=%d)" % (time, n)
  35.  
  36. if __name__ == '__main__':
  37.     sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement