Pregunta

I'm profiling some multi-threaded CPython code.
In order to measure the time it takes to execute a specific code segment, I would like to force the GIL (Global Interpreter Lock) to not switch between threads for that segment. How can this be done?

UPDATE:
Assume the following pseudo-code:

some_code_1()
make_the_interpreter_not_change_thread()
take_start_time()   # time critical
code_to_profile()   # time critical
take_end_time()     # time critical
release_the_interpreter()
some_code_2()

My concern is that the interpreter will switch thread during the 'time critical' profiling period.

¿Fue útil?

Solución

The GIL doesn't switch threads. The GIL is a mutex that prevents multiple threads from executing bytecode at the same time. As such, to prevent thread switching you need to look elsewhere.

You could call sys.setcheckinterval() with a really large value to prevent switching while your code is being profiled.

Whenever you call sys.setcheckinterval(count) the current 'counter' is reset to the new value, so as soon as you call it no thread switch is allowed for at least count bytecode instructions.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top