4

I'm trying to use cProfile to profile some python code. I believe I need to use cProfile.runcall(), not cProfile.run(), since the method I want to run is of the form self.funct() rather than simply funct().

When I try to use cProfile.runcall, detailed here, I get the following error:

AttributeError: 'module' object has no attribute 'runcall'

Has the runcall method been removed from cProfile? If so, is there an alternate method to use of the form cProfile.runcall(self.funct,*args)?

Minimum (not) working example:

import cProfile

def funct(a):
    print a

cProfile.runcall(funct,"Hello")
PProteus
  • 549
  • 1
  • 10
  • 23
  • I recently discovered (the hard way) that the `cProfile` module isn't interchangeable with the `profile` module. In other words the first statement in the Python 2,7 [documentation](https://docs.python.org/2/library/profile.html#module-cProfile) for them, that "Both the `profile` and `cProfile` modules provide the following functions: ...", is patently wrong—and the differences aren'y described anywhere (that I could locate). – martineau Feb 07 '18 at 18:22
  • @martineau I wondered about this, too, but I find it also doesn't work with `profile`. – PProteus Feb 07 '18 at 18:29
  • 1
    PProteus: Oh, in this case it's your mistake. See the [answer](https://stackoverflow.com/a/48671032/355230) I just posted. – martineau Feb 07 '18 at 18:42

1 Answers1

6

In this case, the problem is because runcall() is a method of a Profile class instance, not a module-level function (which is how your code is trying to use it). You need to construct an instance of one first, as shown in code snippet in the documentation.

This seems to work (in Python 2.7.14):

import cProfile

def funct(a):
    print a

pr = cProfile.Profile()
pr.enable()
pr.runcall(funct, "Hello")
martineau
  • 119,623
  • 25
  • 170
  • 301