#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    39
    Rep Power
    2

    Timing Python code


    What is the best way to accurately time code execution?

    Are there different ways for different pieces of code?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    149
    Rep Power
    139
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    611
    Rep Power
    65
    Here is an example ...
    Code:
    ''' timeit_statement101.py
    exploring Python module timeit
    using lambda to insert a statement to be timed 
    '''
    
    import timeit
    
    stmt = "x = 12345679 * 63//7"
    
    # use n=1000000 passes (this is also the default)
    # this way the result will be time per pass in microseconds
    elapsed = lambda stmt, n=1000000: timeit.Timer(stmt).timeit(n)
    
    print("%s took %0.3f micro-seconds/pass" % (stmt, elapsed(stmt)))
    
    ''' result (Python 2.7.4) -->
    x = 12345679 * 63//7 took 0.041 micro-seconds/pass
    '''
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo