Friday, July 18, 2014

Python Profiler

def do_cprofile(func):
    def profiled_func(*args, **kwargs):
        import cProfile
        profile = cProfile.Profile()
        try:
            profile.enable()
            result = func(*args, **kwargs)
            profile.disable()
            return result
        finally:
            profile.print_stats(sort=1)
    return profiled_func

try:
    from line_profiler import LineProfiler

    def do_profile(follow=[]):
        def inner(func):
            def profiled_func(*args, **kwargs):
                try:
                    profiler = LineProfiler()
                    profiler.add_function(func)
                    for f in follow:
                        profiler.add_function(f)
                    profiler.enable_by_count()
                    return func(*args, **kwargs)
                finally:
                    profiler.print_stats()
            return profiled_func
        return inner

except ImportError:
    def do_profile(follow=[]):
        "Helpful if you accidentally leave in production!"
        def inner(func):
            def nothing(*args, **kwargs):
                return func(*args, **kwargs)
            return nothing
        return inner


@do_profile(follow=[fun2])
def fun1():
    fun2()
    pass


@do_cprofile()
def fun2()
    pass

Monday, July 7, 2014

Java cpu profiling with hprof

Set JAVA_OPTS:

-Xrunhprof:cpu=samples,interval=10,depth=8
 
 
There will be a  file called "java.hprof.txt" in your working directory