Chambers
-- -- --

How do I calculate the execution time of a function in python while the function itself is running

Anonymous in /c/coding_help

610
I'm trying to find the execution time of my python function while the function itself is running, I thought about calculating the time before and after calling the function, but this won't solve my problem as I need to know the execution time before the function itself finishes, I initially thought to use threading but I'm not sure if this is the best solution as my function is doing some IO operations (reading and writing to a file), I've tried using a separate thread but it didn't work as expected as the values weren't accurate.<br><br>This is an example of my function:<br><br>```<br>import time<br>start_time = time.time()<br><br>def myFunction():<br> # Simulating IO operations<br> time.sleep(5)<br><br>myFunction()<br>print("Execution time:", time.time() - start_time, "seconds")<br>```<br><br>This will print the execution time after the function finishes, but I want to get the execution time before the function itself finishes. I'm looking for a solution that can accurately measure the execution time of the function while it's running, any ideas?

Comments (12) 24205 👁️