繁体   English   中英

在 Python 中测量实例化 + 方法执行时间

[英]Measure instantiation + method execution time in Python

我有一个 Python class 并想测量实例化 class 并在多个(例如 100 次)运行中执行方法所需的时间。

我注意到第一次运行比连续运行需要更长的时间。 我假设这是由分支预测引起的,因为输入没有改变。 但是,我想测量“从头开始”所花费的时间,即没有分支预测的好处。 请注意,在这种情况下构建真实的输入很困难,因此必须在相同的输入上执行运行。

为了解决这个问题,我尝试在每次运行时创建一个新的 object 并删除旧的 object:

import time

class Myobject:

    def mymethod(self):
        """
        Does something complex.
        """
        pass

def benchmark(runs=100):
    """
    The argument runs corresponds to the number of times the benchmark is to be executed.
    """
    times_per_run = []
    r = range(runs)

    for _ in r:
        t2_start = time.perf_counter()

        # instantiation
        obj = Myobject()
        # method execution
        obj.mymethod()
        del obj

        t2_stop = time.perf_counter()

        times_per_run.append(t2_stop-t2_start)

    print(times_per_run)

benchmark(runs=10)

执行此代码表明每次运行的平均时间差异很大。 第一次运行需要更长的时间。 跨多次运行进行基准测试时,如何消除分支预测的好处?

为了避免预热的好处(s.评论帖子),我使用subprocess模块单独触发运行,同时测量每次运行的时间并随后汇总结果:

def benchmark(runs=100):
    times_per_run = []

    command = "python3 ./myclass.py"

    for _ in range(runs):
        t1_start = time.perf_counter()
        subprocess.run([command], capture_output=True, shell=True, check=False)
        t1_stop = time.perf_counter()

        times_per_run.append(t1_stop - t1_start)

    logging.info(f"Average time per run: {sum(times_per_run) / runs}")

benchmark()

这会产生稳定的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM