Measuring elapsed time with the Time module

前端 未结 10 871
执念已碎
执念已碎 2020-12-02 03:13

With the Time module in python is it possible to measure elapsed time? If so, how do I do that?

I need to do this so that if the cursor has been in a widget for a c

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 03:52

    Another nice way to time things is to use the with python structure.

    with structure is automatically calling __enter__ and __exit__ methods which is exactly what we need to time things.

    Let's create a Timer class.

    from time import time
    
    class Timer():
        def __init__(self, message):
            self.message = message
        def __enter__(self):
            self.start = time()
            return None  # could return anything, to be used like this: with Timer("Message") as value:
        def __exit__(self, type, value, traceback):
            elapsed_time = (time() - self.start) * 1000
            print(self.message.format(elapsed_time))
    

    Then, one can use the Timer class like this:

    with Timer("Elapsed time to compute some prime numbers: {}ms"):
        primes = []
        for x in range(2, 500):
            if not any(x % p == 0 for p in primes):
                primes.append(x)
        print("Primes: {}".format(primes))
    

    The result is the following:

    Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]

    Elapsed time to compute some prime numbers: 5.01704216003418ms

提交回复
热议问题