Python代码时间测试

文章目录

  • jupyter版
  • 基础版
  • 普通装饰器
  • wraps装饰器
  • 封装在类中(力荐)
  • 将时间记录在代码本身
  • 究极版

jupyter版

%%timeit -n 9  # 循环9次

基础版

from time import time

def f():
    pass

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

if __name__ == '__main__':
    main()

普通装饰器

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)

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__)

封装在类中(力荐)

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))

将时间记录在代码本身

追加

from time import time

def f1():
    from random import randint
    from time import sleep
    sleep(randint(1, 9))

def f2():
    pass

def main(functions):
    t = time()
    for f in functions:
        f()
    with open(__file__, 'a', encoding='utf-8') as f:
        text = '\n"""%.2f分钟"""' % ((time() - t) / 60)
        f.write(text)

if __name__ == '__main__':
    main([f1, f2])
"""0.08分钟"""

替换

from time import time
from re import sub

def f1():
    from random import randint
    from time import sleep
    sleep(randint(1, 9))

def f2():
    pass

def main(functions):
    t = time()
    for f in functions:
        f()
    with open(__file__, encoding='utf-8') as f:
        t = (time() - t) / 60
        text = sub('"""[\d.]+分钟"""', '"""%.2f分钟"""' % t, f.read())
    with open(__file__, 'w', encoding='utf-8') as f:
        f.write(text)

if __name__ == '__main__':
    main([f1, f2])
"""0.07分钟"""

究极版

from time import time


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

    def __del__(self):
        print(self)

    def __str__(self):
        t = time() - self.t
        if t < 60:
            return Color.underline('%.2f秒' % t, prints=False)
        elif t < 3600:
            return Color.underline('%.2f分钟' % (t / 60), prints=False)
        else:
            return Color.underline('%.2f小时' % (t / 3600), prints=False)


class Color:

    @staticmethod
    def _wrap_colour(colour, a, prints):
        a = colour + '{}'.format(a) + '\033[0m'
        if prints:
            print(a)
        return a

    @classmethod
    def blue(cls, a, prints=True):
        return cls._wrap_colour('\033[94m', a, prints)

    @classmethod
    def bold(cls, a, prints=True):
        return cls._wrap_colour('\033[1m', a, prints)

    @classmethod
    def cyan(cls, a, prints=True):
        return cls._wrap_colour('\033[96m', a, prints)

    @classmethod
    def darkblue(cls, a, prints=True):
        return cls._wrap_colour('\033[34m', a, prints)

    @classmethod
    def darkcyan(cls, a, prints=True):
        return cls._wrap_colour('\033[36m', a, prints)

    @classmethod
    def green(cls, a, prints=True):
        return cls._wrap_colour('\033[92m', a, prints)

    @classmethod
    def pink(cls, a, prints=True):
        return cls._wrap_colour('\033[95m', a, prints)

    @classmethod
    def purple(cls, a, prints=True):
        return cls._wrap_colour('\033[35m', a, prints)

    @classmethod
    def red(cls, *args):
        for a in args:
            print('\033[91m{}\033[0m'.format(a))

    @classmethod
    def underline(cls, a, prints=True):
        return cls._wrap_colour('\033[4m', a, prints)

    @classmethod
    def yellow(cls, a, prints=True):
        return cls._wrap_colour('\033[93m', a, prints)

    @classmethod
    def background(cls, a, prints=True):
        return cls._wrap_colour('\033[0;7m', a, prints)


if __name__ == '__main__':
    t = Timer()
    print(t)
    Color.blue('blue')
    Color.bold('bold')
    Color.cyan('cyan')
    Color.darkblue('darkblue')
    Color.darkcyan('darkcyan')
    Color.green('green')
    Color.pink('pink')
    Color.purple('purple')
    Color.red('r', 'e', 'd')
    Color.underline('underline', False)
    Color.yellow('yellow')
    Color.background('background')

你可能感兴趣的:(Python实用技巧)