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

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)
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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.