[SOLVED] How to add suffix operations for all python functions?

Issue

I have a a collection of functions inside a file myfile.py and I would like to add a timer print automatically for each of them:
(have around 700 functions)

def myfunXXX() 
   mytime.start()

   mytime.end() 

mytime.start(): to= time.time()
mytime.end():   print(time.time() - t0)

Current solutions are :

  1. Add a decorator manually to all the functions.
  2. Add the code snippet to all the functions

Is there a way to "hack" Python and the function base definition
to add those 2 functions before executing and at execution end
for a set of Python functions ?

Maybe using AST and injecting some string code ?

Solution

sys.setprofile is meant exactly for this.

Make sure you filter according to frame.f_code.co_filename to only stop on the wanted files.

On call event start the timer, on return stop.

Make sure you use time.perf_counter as the timer. The others are less reliable.

Keep in mind, as any other profiler that checks all functions in a module, especially one written in Python, it will slow down your code.


Example:

import sys, time


def create_profile_function(filename):
    _active_frames = {}

    def profile_func(frame, event, arg):
        if event == "call" and frame.f_code.co_filename == filename:
            _active_frames[frame] = time.perf_counter()
        elif event == "return" and frame in _active_frames:
            print(frame.f_code.co_name,
                  time.perf_counter() - _active_frames.pop(frame))

    return profile_func

sys.setprofile(create_profile_function(__file__))

def test():
    print("rawr")
    pass

test()

Output:

rawr
test 0.0005169999785721302

Answered By – Bharel

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.