我正在尝试确定我的python代码的哪些部分运行速度最慢,以便我更好地理解我需要修复的内容。我最近发现cProfile和gprof2dot非常有帮助。我的问题是我没有看到任何关于我正在使用的函数的信息作为回调,我认为这些函数可能运行得很慢。根据我从this answer的理解,cProfile仅在主线程中默认工作,我猜测回调使用单独的线程。如果您正在使用线程库,那么答案显示了让事情正常工作的方法,但我无法让它适用于我的案例。
以下是我的代码的大致内容:
import rospy
import cv
import cProfile
from numpy import *
from collections import deque
class Bla():
def __init__( self ):
self.image_data = deque()
self.do_some_stuff()
def vis_callback( self, data ):
cv_im = self.bridge.imgmsg_to_cv( data, "mono8" )
im = asarray( cv_im )
self.play_with_data( im )
self.image_data.append( im )
def run( self ):
rospy.init_node( 'bla', anonymous=True )
sub_vis = rospy.Subscriber('navbot/camera/image',Image,self.vis_callback)
while not rospy.is_shutdown():
if len( self.image_data ) > 0:
im = self.image_data.popleft()
self.do_some_things( im )
def main():
bla = Bla()
bla.run()
if __name__ == "__main__":
cProfile.run( 'main()', 'pstats.out' ) # this could go here, or just run python with -m cProfile
#main()
有关如何获取vis_callback函数的cProfile信息的任何想法?是通过修改脚本本身,还是使用python -m cProfile
或其他命令行方法更好?
我猜测它要么是读取图像,要么将它们附加到队列中,这会慢。我的直觉是将它们存储在队列中是一件可怕的事情,但是我需要用matplotlib显示它们,如果它不在主线程中则拒绝工作,所以我想看看损坏到底有多糟糕有这个解决方法