python - 补丁模块进入和退出 - Python
问题描述
我有一个名为 my_module 的模块,我想测量它的性能。
my_module
有多个功能,我想做的是,每当调用模块中的任何功能时
- 记下入场时间
- 记下退出时间
所以假设我运行了这个 -my_module.func('blah')
我想打印
- 函数调用开始于 100001201
- 函数调用结束于 100001312
对于模块中的任何功能。
我不能对模块文件进行任何直接更改,因为它也必须在其他地方使用。我只需要这个来打印性能测试脚本。
请帮忙。
解决方案
我是在 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))
注意:要使其适用于您自己的模块,只需将“numpy”更改getmembers(numpy, isfunction)
为您导入模块的名称。
现在,我们的 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
.
推荐阅读
- php - 使用 XAMPP 在 Windows 10 中安装 go-pear.phar 时出错
- vue.js - 如何在 Nuxt JS 中将变量值从“页面”传递到“布局”?
- java - 尝试在 QT 项目中调用 Java 代码时找不到类异常
- apache-kafka-streams - 使用 Kafka Streams 分配多个主题的消费者
- node.js - VSCode Task 运行各种节点命令
- python - python中的CSV标头
- reactjs - 使用 mobx 获取数据进入无限循环
- c# - EF Core:无法跟踪实体类型的实例,因为另一个实例具有相同的键值
- javascript - 第 530 行的错误 1062 (23000):重复条目 '20190617051131-apply-schema.js' 用于键 'PRIMARY'
- laravel - Laravel 附加在关联键上