1

I would like to get the total time as given by the timeit module (so user + sys time) for a block of code that is executed many times in my script (it is inside a loop). I know the timeit module can give you these times by using %time [code here], but how do I do something like this for multiple lines of code?

So I would like to do something like:

# Some code here
x = start_time() # just something to mark the start of timing
# code I want to know the time of
user, system, elapsed = stop_time(x) # whatever marks the end of timing

This question is really much like the one here: Get time of execution of a block of code in Python 2.7 However in this case the person asking the question was mostly interested in elapsed time and so all answers tell how to do this. I have found many examples of how to do this but I would really like to get user and sys time.

I really hope someone can help me with this. Thanks in advance

Community
  • 1
  • 1
Iris
  • 131
  • 5
  • You can't put it in a function? Then all you have to do is time the function – MotKohn Dec 15 '16 at 04:43
  • It is already in a function (but I want to time part of the code in the function, not all of it) so I did not think of that.. I will try right now to see if I can build a function around the specific code block. Thanks for the suggestion. – Iris Dec 15 '16 at 04:53
  • It seemed like a really good idea but now I realise I wouldn't know how to get the time into variables but more importantly even, how do I get the actual output of the function that I would create? I'm sorry if this is a trivial question, I'm not a very experienced programmer.. – Iris Dec 15 '16 at 05:01
  • something like `timeit('print(your_function', number=5, globals=globals())` may work, but that will also time the time that print is executing. The reason for `number=5` is because by default it executes 100,000 times that would be a lot of output. – MotKohn Dec 15 '16 at 05:25
  • Thank you for your input. Why are there quotes before print and after your_function ? And I only want it to be executed once, but I guess I could just set numbers to 1? And globals would cause whatever variables I create inside the function to also exist outside the function, so I could continue my program like nothing has changed? – Iris Dec 15 '16 at 05:32

0 Answers0