python code profile

Solutions on MaxInterview for python code profile by the best coders in the world

showing results for - "python code profile"
Pedro
23 Feb 2016
1import os
2import cProfile
3import pstats
4# gprof2dot must be installed
5# dot must be installed 
6
7def profile_function(function_call: str, sort_stat='tottime'):
8
9    name_file = function_call.split('(')[0]
10
11    cProfile.run(function_call, f'code_profiling/{name_file}.dat')
12
13    with open(f'code_profiling/{name_file}.txt', 'w') as f:
14        p = pstats.Stats(f'code_profiling/{name_file}.dat', stream=f)
15        p.sort_stats(sort_stat).print_stats()
16
17    com = f'gprof2dot -f pstats code_profiling/{name_file}.dat | dot -Tpng -o code_profiling/{name_file}.png'
18
19    os.system(com)
20
21function_call = "any_function(arg_1, arg_2)"
22
23profile_function(function_call)