Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find running time of a thread in Python

I have a multi-threaded SMTP server. Each thread takes care of one client. I need to set a timeout value of 10 seconds on each server thread to terminate dormant or misbehaving clients.
I have used the time.time(), to find the start time and my checkpoint time and the difference gives the running time. But I believe it gives the system time and not the time this thread was running.
Is there a Thread 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 a loop and does not come out of the while loop.

like image 768
ango Avatar asked Nov 18 '12 17:11

ango


People also ask

How is thread execution time calculated in Python?

current_thread(). thread_duration = end — start , we used start = time. perf_counter() and end = time. perf_counter() to calculate the thread execution time and then assigned it to thread object as thread_duration .

How do I check if a Python thread is running?

In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.

What is threading timer in Python?

The Python Timer class is used to perform an operation or have a function run after a specified period has passed. The threading class has a subclass called the class timer. In technical terms, we will create Timer objects when we need time-bound actions (methods), in technical terms.


1 Answers

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

time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID)

Python 3.7 additionally introduced an analogous time.clock_gettime_ns.

Detailed docs are exactly where you'd expect but the feature is pretty straightforward straight out of the box.

like image 86
hemflit Avatar answered Oct 26 '22 03:10

hemflit