3

I created a simple application, and I realised that my code is running extremely slow. This application included calling the same method over and over again. I tried investigating the problem, and it turned out that calling the same function / method several times resulted in Python sometimes taking 15 milliseconds to execute an empty function (pass).

I'm running windows 10 Home 64 bit on a Lenovo ThinkPad, i7 CPU The less code the function / method has, the smaller the chance of having a 15ms runtime, however, it never goes away.

Here's the code:

import time

class Clock:

    def __init__(self):
        self.t = time.time()

    def restart(self):
        dt = time.time() - self.t
        t = time.time()
        return dt * 1000


def method():
    pass



for i in range(100000):
    c = Clock()

    dt = c.restart()
    if dt > 1.:
        print(str(i) + ' ' + str(dt))

I'd expect that I never get anything printed out, however an average result looks like this:

6497 15.619516372680664

44412 15.622615814208984

63348 15.621185302734375

On average 1-4 out of 100000 times the time elapsed between starting the clock and getting the result (which is an empty function call and a simple subtraction and variable assignment) the elapsed time is 15.62.. milliseconds, which makes the run time really slow. Occasionally the elapsed time is 1 millisecond.

Thank you for your help!

DeshDeep Singh
  • 1,817
  • 2
  • 23
  • 43

1 Answers1

2

In your code you are making the call to time.time() twice which would require the system to retrieve the time from the OS. You can read here How does python's time.time() method work?

As you mentioned you used Windows, it is probably better for you to use time.clock() instead and will defer you to read this link instead since they do a much better job explaining. https://www.pythoncentral.io/measure-time-in-python-time-time-vs-time-clock/

Also the link takes garbage collection into account of performance and gives the ability to remove it during testing.

Hope it answers your questions!

Haris Nadeem
  • 1,322
  • 11
  • 24