Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing a task In Python [duplicate]

Tags:

python

time

I've been trying to figure this out for a while now and I haven't been able to. Basically what I want to do is get the Time it takes to complete a specific task.

For Example:

def find(x):
  if x in stuff:
    return "X was found, Search Time: [TIME IT TOOK]"

I would like it to be something like "Search Time: 0.03 seconds". This is a really bad example but it's midnight and i'm trying to complete a python project for school so all answers are greatly appreciated.

Thanks

like image 372
Arman Shah Avatar asked Dec 10 '14 07:12

Arman Shah


1 Answers

As I understand your goal, it's not a profiler that you're after. For something as simple as logging how long a specific processing step took (wall-clock time), I usually use time.time() to get the start and end times and take the difference of them.

Example:

import time

start = time.time()
# do something
pass
end = time.time()
delta = end - start
print "took %.2f seconds to process" % delta

For a possibly greater resolution (microseconds), and for its independence from the system clock, also have a look at time.clock(). Note that this measures CPU time, not wall-clock time (at least on Linux - this may not be what you need).

For reference:

  • https://docs.python.org/2/library/time.html#time.time
  • https://docs.python.org/2/library/time.html#time.clock
  • http://en.wikipedia.org/wiki/Wall-clock_time
like image 76
moooeeeep Avatar answered Oct 13 '22 01:10

moooeeeep