【问题标题】:Python wrapper script to measure execution time of another python file [duplicate]Python包装脚本来测量另一个python文件的执行时间[重复]
【发布时间】:2020-11-24 02:32:29
【问题描述】:

如何制作一个 Python 包装脚本,以使用时间测量另一个脚本或另一个 .py 文件的执行时间?

【问题讨论】:

    标签: python wrapper


    【解决方案1】:

    你可以使用定时器模块

    from timeit import default_timer as timer
    start = timer()
    function_you_want_to_time()
    # or import your script here
    # import script_to_time
    end = timer()
    elapsed = str(end - start)
    print(f'Run time in seconds: {elapsed}')
    

    【讨论】:

    • 我实际上需要对整个脚本而不是脚本内部的函数进行计时。示例我有一个 benchrun.py ,我需要使用 wrapper.py 获取它的执行时间
    • 它仍然有效,只需将function_you_want_to_time() 替换为import benchrun
    【解决方案2】:

    我最近有一个类似的问题要解决,我的解决方案是编写一个可导入的模块,我可以通过import MyModule 调用它,它将捕获脚本执行时间以及任何运行时异常,然后将结果推送到数据仓库。

    我的解决方案是这样的

    import MyModule
    
    def main():
        print("do work")
    
    if __main__ == '__main__':
        try:
            main()
        except Exception as e:
            MyModule.script.script_execution(e)
        else:
            MyModule.script.script_execution()
    

    MyModule 想要这样的东西

    MyModule.__init__.py

    from datetime import datetime
    
    
    class ScriptExeuction:
        def __init__(self):
            self.start_time = datetime.now()
    
        def script_execution(self, exception=None):
            self.end_time = datetime.now()
            print(f"Execution took {self.end_time - self.start_time}")
    
    
    if __name__ == '__main__':
        pass
    else:
        script = ScriptExeuction()
    

    当然,您需要扩展它以将数据放在您想要的位置,但您可以轻松扩展 ScriptExecution 类来处理将数据推送到某处的逻辑,并且您可以捕获脚本中发生的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 2016-04-22
      • 1970-01-01
      • 2014-01-19
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      相关资源
      最近更新 更多