7

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

Bharadwaj Srigiriraju
  • 2,196
  • 4
  • 25
  • 45
Arman Shah
  • 111
  • 1
  • 6
  • 5
    You can use [timeit](https://docs.python.org/2/library/timeit.html) module. – Marcin Dec 10 '14 at 07:14
  • 1
    This is just the time taken to run, time complexity is different. – jamylak Dec 10 '14 at 07:14
  • That's not time complexity, it's just wall-clock time. Time complexity reflects the scalability of an algorithm (to get wall-clock time, use timeit, as Marcin suggests) – Jon Kiparsky Dec 10 '14 at 07:14
  • How else you would interpret "Search Time: [TIME IT TOOK]"? I dont think its `O(log(n))` or whatever. I think its about time in seconds or microseconds. – Marcin Dec 10 '14 at 07:17
  • True, `timeit` is the right direction but it would be nice to see the best way of using it and saving the result at the same time – jamylak Dec 10 '14 at 07:17
  • @Marcin Yeah but the question states "Time Complexity" instead of just time – jamylak Dec 10 '14 at 07:18
  • Yep, the question is little confusing. Hopefully OP can clarify. – Marcin Dec 10 '14 at 07:18
  • Its not confusing, we were both just correcting a small misuse of a word. he obviously wants the time in seconds or milliseconds etc – jamylak Dec 10 '14 at 07:20
  • @jamylak: come on, do we always need to spoon feed people? A single Google search of "timeit python" provides tons of example pages, including a dupe on SO. – Matteo Italia Dec 10 '14 at 07:21
  • @MatteoItalia There is a dupe, so i marked it as a duplicate. – jamylak Dec 10 '14 at 07:24

1 Answers1

9

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:

moooeeeep
  • 31,622
  • 22
  • 98
  • 187