我正在尝试将cProfiling与python结合使用。
我的python项目具有以下目录结构:
my-project
├── src
│ ├── lib
│ └── app
│ └── data
│ └── car_sim.py
│
│
│
│
├── ptests
│ ├── src
│ └── lib
│ └── app
│ └── data
│ └── cprofile_test.py
我在[[car_sim.py内部有一个函数,我想对其进行剖析,它称为“ sim_text”。它包含一个函数:
#car_sim.py
import os
class RootSimulator:
def sim_text(self, text):
return text
我在中使用以下代码:cprofile_test.py
#cprofile_test.py
import cProfile
import pstats
import io
import src.lib.app.data.car_sim as car_sim_functions
pr = cProfile.Profile()
pr.enable()
text = 'my blabla sentence' #i can pass in this text below i guess...
#how do i pass to the below????!!
my_result = car_sim_functions.RootSimulator.sim_text()
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('tottime')
ps.print_stats()
with open('test.txt', 'w+') as f:
f.write(s.getvalue())
现在...当我使用命令运行它时python -m cProfile ptests / src / lib / app / data / cprofile_test.py我收到以下错误:
TypeError:sim_text()缺少2个必需的位置参数:'self'和'text'我的问题是...它需要2个arg,所以我该如何传递“ self” arg。对于第二个arg,“文本”我可以传入一个值,没问题。
class RootSimulator:
def sim_text(self, text):
return text
在RootSimulator
的实例上定义实例方法。您正在尝试从类本身调用sim_text
。您需要创建一个实例:
simulator = car_sim_functions.RootSimulator() my_result = simulator.sim_text()
如果实际上不需要将sim_text()
附加到模拟器的实例,则也许根本不需要类(只需将其设为普通函数即可,或者可以将其设为静态方法:
class RootSimulator: @staticmethod def sim_text(text): return text
请注意,它不再需要self
。