我有一个在Linux上运行的C++应用程序,我正在优化它.如何确定代码的哪些区域运行缓慢?
我现在使用cProfile但是我觉得编写pstats代码只是为了查询统计数据很繁琐.
我正在寻找一个可视化工具,向我展示我的Python代码在CPU时间和内存分配方面的作用.
Java世界的一些例子是visualvm和JProfiler.
我知道KCachegrind for Linux,但我更喜欢可以在Windows/Mac上运行而无需安装KDE的东西.
我基本上做了以下事情:
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
# ... my code did something ...
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.dump_stats('stats.dmp') # dump the stats to a file named stats.dmp
Run Code Online (Sandbox Code Playgroud)
所以现在我将名为'stats.dmp'的文件存储在离线状态.
如何使用pstats分析此文件供人类使用?
提前致谢.
是否有Python的分析器可以渲染像Kcachegrind的Callee地图视图?
在这里我可以获得线程完成所需的时间。如何获取线程消耗的内存。
import threading
import time
class mythread(threading.Thread):
def __init__(self,i,to):
threading.Thread.__init__(self)
self.h=i
self.t=to
self.st=0
self.end=0
def run(self):
self.st =time.time()
ls=[]
for i in range(self.t):
ls.append(i)
time.sleep(0.002)
self.end=time.time()
print "total time taken by {} is {}".format(self.h,self.end-self.st)
thread1=mythread("thread1",10)
thread2=mythread("thread2",20)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Run Code Online (Sandbox Code Playgroud) 我有一组python脚本,我想用kernprof https://github.com/rkern/line_profiler进行分析,但我也希望能够在没有kernprof的正常执行期间运行它.
在没有kernprof的情况下执行期间忽略未定义的@profile的优雅方法是什么?或任何其他装饰.
示例代码:
@profile
def hello():
print('Testing')
hello()
Run Code Online (Sandbox Code Playgroud)
运行:
kernprof -l test.py
Run Code Online (Sandbox Code Playgroud)
在@profile方法上正确执行探查器
运行:
python test.py
Run Code Online (Sandbox Code Playgroud)
返回错误:
Traceback (most recent call last):
File "test.py", line 1, in <module>
@profile
NameError: name 'profile' is not defined
Run Code Online (Sandbox Code Playgroud)
希望避免在任何地方捕获此错误,因为我希望代码执行,就好像@profile是一个no-op,而不是用kernprof调用它.
谢谢!-Laura
编辑:我最终使用cProfile与kcachegrind完全避免装饰器.
python -m cProfile -o profile_data.pyprof run_cli.py
pyprof2calltree -i profile_data.pyprof && qcachegrind profile_data.pyprof.log
Run Code Online (Sandbox Code Playgroud)