0

How to profile one function with cprofiler?

label = process_one(signature)

become

import cProfile

label = cProfile.run(process_one(signature))

but it didn't work :/

Fractale
  • 1,503
  • 3
  • 19
  • 34
  • I googled your question and found this link that answers it: https://julien.danjou.info/blog/2015/guide-to-python-profiling-cprofile-concrete-case-carbonara – sisanared Oct 19 '16 at 13:34

2 Answers2

4

You can write some decorator which will be helpful for profiling any function in general with cProfile. This helps me to quickly get stats when I need them.

import cProfile
import pstats
import StringIO
import commands


def qprofile(func):
    def profiled_func(*args, **kwargs):
        if 'profile' in kwargs and kwargs['profile']:
            kwargs.pop('profile')
            profile = cProfile.Profile()
            try:
                profile.enable()
                result = func(*args, **kwargs)
                profile.disable()
                return result
            finally:
                s = StringIO.StringIO()
                ps = pstats.Stats(
                    profile, stream=s).strip_dirs(
                ).sort_stats('cumulative')
                ps.print_stats(30)
                print s.getvalue()
        else:
            result = func(*args, **kwargs)
            return result
    return profiled_func

@qprofile
def process_one(cmd):
    output = commands.getoutput(cmd)
    return output

# Function is profiled if profile=True in kwargs
print(process_one('uname -a', profile=True))

Sample Output:

         7 function calls in 0.013 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.013    0.013 qprofiler.py:29(process_one)
        1    0.000    0.000    0.013    0.013 commands.py:48(getoutput)
        1    0.000    0.000    0.013    0.013 commands.py:56(getstatusoutput)
        1    0.013    0.013    0.013    0.013 {method 'read' of 'file' objects}
        1    0.000    0.000    0.000    0.000 {posix.popen}
        1    0.000    0.000    0.000    0.000 {method 'close' of 'file' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Linux chronin 4.4.0-42-generic #62-Ubuntu SMP Fri Oct 7 23:11:45 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Please refer official documentation for any call specific references, https://docs.python.org/2/library/profile.html

Sanket Sudake
  • 763
  • 6
  • 18
1

according to documentation (https://docs.python.org/2/library/profile.html) it should be cProfile.run('process_one(signature)')

also, look at the answer https://stackoverflow.com/a/17259420/1966790

Community
  • 1
  • 1
MateuszL
  • 2,751
  • 25
  • 38