2022年 11月 5日

Python计时器

文章目录

  • 概述
  • Python3计时器
    • jupyter版
    • 函数版
    • 普通装饰器+函数版
    • wraps装饰器+函数版
    • 封装在类中(力荐)
    • 封装在类中+单例对象(力荐)
  • Java计时方法

概述

计时器,用于计算程序运行时间

Python3计时器

jupyter版

%%timeit -n 9  # 计时9次
  • 1

函数版

from time import time

def f():
    pass

def main():
    t = time()
    f()
    print('时间消耗:%.2f秒' % (time() - t))

if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

普通装饰器+函数版

def fn_timer(fn):
    def function_timer(*args, **kwargs):
        """装饰器"""
        from time import time
        t = time()
        result = fn(*args, **kwargs)
        print('【%s】运行%.2f秒' % (fn.__name__, time() - t))
        return result
    return function_timer

@fn_timer
def f():
    pass

help(f)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

wraps装饰器+函数版

from time import time
from functools import wraps

def fn_timer(fn):
    @wraps(fn)
    def function_timer(*args, **kwargs):
        t = time()
        result = fn(*args, **kwargs)
        print('【%s】运行时间:%.2f秒' % (fn.__name__, time() - t))
        return result
    return function_timer

@fn_timer
def f():
    """用wraps后可以获取help"""
    pass

print(f.__doc__)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

封装在类中(力荐)

from time import time
class Timer:
    def __init__(self):
        self.t = time()
    def __del__(self):
        print(time() - self.t)
        print('%.2f分钟' % ((time() - self.t) / 60))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

封装在类中+单例对象(力荐)

from time import time, strftime


class Timer:
    def __init__(self):
        self.t = time()
        print('开始时间:' + self.now)

    def __del__(self):
        print('结束时间:' + self.now)
        if self.__str__():
            print('运行时间:' + str(self))

    def __str__(self):
        t = self.second
        if t < .5:
            return ''
        elif t < 60:
            return '%.2fs' % t
        elif t < 3600:
            return '%.2fmin' % (t / 60)
        else:
            return '%.2fh' % (t / 3600)

    @property
    def second(self) -> float:
        """程序运行秒数"""
        return time() - self.t

    @property
    def now(self) -> str:
        return strftime('%Y-%m-%d %H:%M:%S')

    def __new__(cls):
        if not hasattr(Timer, '_instance'):
            Timer._instance = object.__new__(cls)
        return Timer._instance
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

Java计时方法

long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
  • 1
  • 2
  • 3