0

When I write a code, I put time related codes in the beginning and at the end to see how many seconds it takes. Is it possible to write it as a module, and refer to it when i write a code just with a single line of code?

import time
x1= time.strftime('%s')

Code
Code 
Code

x2= time.strftime('%s')
timediff = int(x2)-int(x1)
print 'it took ', timediff,'seconds'

So it should look like this I guess,

def StopWatch():
     x1 =time.strftime('%s')
     Wait for code to run
     x2 =time.strftime('%s')
     timediff = int(x2)-int(x1)
     print 'it took ', timediff,'seconds'

thanks

3
Contributors
2
Replies
5
Views
7 Years
Discussion Span
Last Post by snippsat
0

Maybe this?

def main():
    pass # Do something here.


def StopWatch(func):
     x1 =time.strftime('%s')
     func()
     x2 =time.strftime('%s')
     timediff = int(x2)-int(x1)
     print 'it took ', timediff,'seconds'

if __name__ == "__main__":
    StopWatch(main)
0
import time

def foo():
    for i in range(100000):
        i

def time_code(arg):    
    start = time.clock()
    arg()
    end = time.clock()
    print 'Code time %.3f seconds' % (end - start)

if __name__ == '__main__':
    time_code(foo)

Most off the time code is to fast to measure only with one run,that`s why man use timeit modulen for measurement of code time.
From command line or script.

C:\>python -m timeit "for i in xrange(100): pass"
1000000 loops, best of 3: 1.77 usec per loop

#Are tuple faster than list?
C:\>python -m timeit (1,2,3,4)
10000000 loops, best of 3: 0.0226 usec per loop

C:\>python -m timeit [1,2,3,4]
10000000 loops, best of 3: 0.194 usec per loop
#Yes tuple are faster than list
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.