How to find thread runtime in Python

I have a multi-threaded SMTP server. Each thread takes care of one client. I need to set a timeout value for 10 seconds on each server thread in order to terminate a sleeping or erroneous client.
I used time.time() to find the start time and time of my checkpoint, and the difference gives the runtime. But I believe that this gives the system time, not the time when this thread is running.
Is there a local timer API in Python?

  import threading stop = 0 def hello(): stop = 1 t=threading.Timer(10,hello) t.start() while stop != 1: print stop print "stop changed" 

This prints 0 (initial stop) in the loop and does not exit the while loop.

+5
source share
5 answers

There is no mention of "thread synchronization" in the python documentation. Either the clock is system-wide, or system-wide. In particular, time.clock measures the time of a process, and time.time returns the system time.

In python3.3, the timing APIs have been revised and improved, but still I don't see a single timer that will return the process time spent by a single thread.

Also note that even if possible, it is not at all easy to write such a timer. Timers are OS specific, so you will need to write a different version of the module for each OS. If you want to profile a specific action, just run it without threads. When streaming time, it either works as expected, or it is much slower due to the OS, in which case you can not do anything about it (at least if you do not want to write a patch that "fixes", GIL or removes it safely).

+8
source

The stop value of the hello function is local, not global.

Add the following:

 def hello(): global stop stop = 1 
+2
source

Python has progressed for 6 years since this question was asked, and in version 3.3 it introduced a tool for exactly what was asked here:

time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID)

Python 3.7 also introduces an analogue of time.clock_gettime_ns .

Detailed documents are exactly where you expected, but this function is quite simple right out of the box.

+2
source

I am posting a sample code that can measure the running time of a thread, you can change the code to use it with your function.

  import time import threading def hello(): x = 0 while x < 100000000: pass x += 1 start = time.clock() t = threading.Thread(target = hello, args = ()) t.start() t.join() end = time.clock() print "The time was {}".format(end - start) 

On my system, this gave a time of 8.34 seconds.

0
source

Python 3.7 adds the time.thread_time() method which seems to do what is needed for this question. According to the docs , this depends on the flow and excludes the time spent sleeping.

0
source

Source: https://habr.com/ru/post/1446796/


All Articles