Get timer ticks in Python

后端 未结 6 721
一整个雨季
一整个雨季 2020-12-05 01:46

I\'m just trying to time a piece of code. The pseudocode looks like:

start = get_ticks()
do_long_code()
print \"It took \" + (get_ticks() - start) + \" secon         


        
6条回答
  •  半阙折子戏
    2020-12-05 02:48

    If you have many statements you want to time, you could use something like this:

    class Ticker:
        def __init__(self):
            self.t = clock()
    
        def __call__(self):
            dt = clock() - self.t
            self.t = clock()
            return 1000 * dt
    

    Then your code could look like:

    tick = Ticker()
    # first command
    print('first took {}ms'.format(tick())
    # second group of commands
    print('second took {}ms'.format(tick())
    # third group of commands
    print('third took {}ms'.format(tick())
    

    That way you don't need to type t = time() before each block and 1000 * (time() - t) after it, while still keeping control over formatting (though you could easily put that in Ticket too).

    It's a minimal gain, but I think it's kind of convenient.

提交回复
热议问题