import cProfile
import pstats
import os


# 性能分析装饰器定义
def do_cprofile(filename):
    """
    Decorator for function profiling.
    """
    def wrapper(func):
        def profiled_func(*args, **kwargs):
            # Flag for do profiling or not.
            DO_PROF = False
            if DO_PROF:
                profile = cProfile.Profile()
                profile.enable()
                result = func(*args, **kwargs)
                profile.disable()
                # Sort stat by internal time.
                sortby = "tottime"
                ps = pstats.Stats(profile).sort_stats(sortby)
                ps.dump_stats(filename)
            else:
                result = func(*args, **kwargs)
            return result
        return profiled_func
    return wrapper
[((16, 26, 16, 44), 'cProfile.Profile', 'cProfile.Profile', ({}, {}), '()', False, 'import cProfile\n'), ((22, 21, 22, 42), 'pstats.Stats', 'pstats.Stats', ({(22, 34, 22, 41): 'profile'}, {}), '(profile)', False, 'import pstats\n')]