0

我正在对导入进行一些测试,我想测试使用函数装饰器导入某些包的速度。这是我的代码:

import time


def timeit(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print(f'{func.__name__} executed in {end - start} second(s)')
    return wrapper


@timeit
def import_matplotlib():
    import matplotlib.pyplot


@timeit
def import_numpy():
    import numpy


import_matplotlib()
import_numpy()

输出

import_matplotlib executed in 0.4385249614715576 second(s)
import_numpy executed in 0.0 second(s)

鉴于没有立即导入 numpy,这不是预期的输出。这里发生了什么,如何解决?谢谢你。

编辑

如果我对 import_numpy() 进行此更改:

@timeit
def import_numpy():
    import numpy
    time.sleep(2)

输出变成这样:

import_matplotlib executed in 0.4556155204772949 second(s)
import_numpy executed in 2.0041260719299316 second(s)

这告诉我我的装饰器功能没有任何问题。为什么会出现这种行为?

4

1 回答 1

0

尝试使用timeit 模块?它是为此目的而构建的,并使代码更简单。

>>> import timeit
>>> timeit.timeit(stmt='import numpy')
0.13844075199995132
于 2021-04-19T09:21:06.290 回答