Using cProfile results with KCacheGrind

Adam Luchjenbroers picture Adam Luchjenbroers · Dec 13, 2009 · Viewed 25.1k times · Source

I'm using cProfile to profile my Python program. Based upon this talk I was under the impression that KCacheGrind could parse and display the output from cProfile.

However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the status bar and sits there displaying nothing.

Is there something special I need to do before my profiling stats are compatible with KCacheGrind?

...
if profile:
    import cProfile

    profileFileName = 'Profiles/pythonray_' + time.strftime('%Y%m%d_%H%M%S') + '.profile'

    profile = cProfile.Profile()
    profile.run('pilImage = camera.render(scene, samplePattern)')

    profile.dump_stats(profileFileName)
    profile.print_stats()
else:            
    pilImage = camera.render(scene, samplePattern)
...

Package Versions

  • KCacheGrind 4.3.1
  • Python 2.6.2

Answer

Mikael Lepistö picture Mikael Lepistö · Aug 25, 2010

With cProfile you can also profile existing programs, without making any separate profiling script. Just run program with profiler

python -m cProfile -o profile_data.pyprof script_to_profile.py

and open profile data in kcachegrind with pyprof2calltree, whose -k switch automatically opens data in kcachegrind

pyprof2calltree -i profile_data.pyprof -k

For example profiling whole paster server and webapp would be done like this

python -m cProfile -o pyprof.out `which paster` serve development.ini

pyprof2calltree can be installed with easy_install.