Python Glossary Русский

all Python 3threadingfunction

threading.setprofile()

tracing and profiling

Sets a profiling function for threads started after the call: each new thread passes it to sys.setprofile() before run().

Syntax

threading.setprofile(func)  # func(frame, event, arg)

The catch is the word 'new': threads already running and the calling thread itself, usually the main one, do not get the function. The current thread also needs sys.setprofile(), and since 3.12 setprofile_all_threads() covers all of them. The function receives call/return and c_call/c_return events, but not per-line ones — that is settrace(). It is rarely written by hand: cProfile and third-party profilers do it, and any profiling slows the program noticeably.

Examples

import threading
calls = []
def prof(frame, event, arg):
    if event == 'call':
        calls.append(frame.f_code.co_name)
def work():
    pass
threading.setprofile(prof)
work()  # главный поток не профилируется
t = threading.Thread(target=work)
t.start()
t.join()
threading.setprofile(None)
print(calls.count('work'))  # → 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy