【问题标题】:Patch module entry and exit - Python补丁模块进入和退出 - Python
【发布时间】:2021-03-07 05:14:43
【问题描述】:

我有一个名为 my_module 的模块,我想测量它的性能。

my_module 有多个功能,我想做的是,每当调用模块中的任何功能时

  • 记下进入时间
  • 记下退出时间

假设我运行了这个 - my_module.func('blah')

我想打印

  • 函数调用开始于 100001201
  • 函数调用结束于 100001312

对于模块中的任何功能。

我无法对模块文件进行任何直接更改,因为它也必须在其他地方使用。我只需要这个来打印性能测试脚本。

请帮忙。

【问题讨论】:

    标签: python python-3.x mocking monkeypatching


    【解决方案1】:

    我是在 Numpy 模块上做的,所以你应该可以对任何模块使用相同的方法:

    import numpy as np                           # import the module you want to be logged
    from inspect import getmembers, isfunction   # These will give us the functions in a module
    import time                                  # for logging the time
    
    class Object(object):                        # make a dummy class on which we can do "setattr()"
        pass
    
    numpy_with_time_logger = Object()            # We are going to make numpy_with_time_logger work exactly like Numpy except that it will also print start and end times
    
    
    def return_call_time_logger(f):              # This function takes in a function and returns a new function!
        def call_time_logger(*args, **kargs):    # This function is going to substitute f. It runs f(), but it also prints the times.
            print(f'Function call started at {time.time()}')
            ret_val = f(*args, **kargs)
            print(f'Function call ended at {time.time()}')
            return ret_val
        return call_time_logger
    
    for f_name, f in getmembers(numpy, isfunction): # For every function inside numpy module
        # Set numpy_with_time_logger.f_name to be return_call_time_logger(f)
        setattr(numpy_with_time_logger, f_name, return_call_time_logger(f))
    

    注意:要使其适用于您自己的模块,只需将getmembers(numpy, isfunction) 中的“numpy”更改为您导入的模块的名称即可。

    现在,我们的 numpy_with_time_logger 对象设置为与 Numpy 完全相同,但它也会打印开始和结束时间。所以尝试通过 numpy_with_time_logger 使用任何 numpy 的函数:

    print(numpy_with_time_logger.asarray([1,2]))
    
    

    输出是:

    start time 1615096471.112301
    end time 1615096471.1134446
    array([1, 2])
    

    这个方法的一个问题:

    如果你调用numpy_with_time_logger.func1()numpy_with_time_logger.func1()调用numpy.func2(),那么你只会得到func1的时间日志,你不会得到func2的时间日志。

    要访问 Numpy 模块中定义的全局变量,只需继续使用 numpy,例如numpy.int32.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多