i did go thru a google search and found some functions .. but those results where horrifying , i guess i am using a wrong method of finding time .

def test():
    "Stupid test function"
    L = []
    for i in range(100):

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

The time taken to execute or displayed was 21.0178511143

is thats true .. then is python that slow ...? cuz in C its a fraction of a second ...

Recommended Answers

All 6 Replies

The Timer.timeit function runs your function 1 000 000 times by default, so your function runs in 21 microseconds on average.
If you want to run a program only once and measure its performance, you should use the 'cProfile' or 'profile' module. See http://docs.python.org/library/profile.html.

For running code once you can write a function like this.

import time

def test():
    "Stupid test function"
    L = []
    for i in range(100):

def time_code(arg):
    '''For running code once,and take time'''
    start = time.clock()
    end = time.clock()
    print 'Code time %.6f seconds' % (end - start)

if __name__ == '__main__':
Code time 0.000187 seconds

Most off the time you are dealing with code that are to fast to only run once.
That`s where timit is fine.

Here you see that list comprehensions is a litte faster than ordinary for loop.
Here i set timit to run 1000 loops.

import timeit

test = ''' 
L = []
for i in range(1000):
#The same code as test written with list comprehensions
test_lc = '''
L = [i for i in range(1000)]      

print timeit.Timer(stmt = test).timeit(number=1000)

print timeit.Timer(stmt = test_lc).timeit(number=1000)

how to interpret the time command .....

i executed a python program using time command as prefix during execution
and fetched this as output

real 0m7.741s real time is almost the same as user time
user 0m7.440s
sys 0m0.008s

But when i tried optimising ( algorithmically ) my python program i fetched another output

real 0m4.419s // the real time is way lesser than user time
user 0m7.660s
sys 0m0.052s

Well how do i decide which one of my implementation is better ,,,... does it depend on real time or user time .. ?

How do you get those times?

well while executing u just write

$ time python program.py

"program output "

that time is printed in the end ....


is that the incorrect way to check time for execution ?

Yes, snippsat told you how to do it correctly some posts before.

Can you try like that, eihter of the ways, they do the task pretty nicelly.

Happy coding

Be a part of the DaniWeb community

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