如何在Python中查找线程的运行时间 [英] How to find running time of a thread in Python

查看:72
本文介绍了如何在Python中查找线程的运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程 SMTP 服务器.每个线程负责一个客户端.我需要在每个服务器线程上设置 10 秒的超时值以终止休眠或行为不端的客户端.
我使用了 time.time(),找到开始时间和我的检查点时间,差异给出了运行时间.但我相信它给了系统时间,而不是这个线程运行的时间.
Python 中是否有 Thread 本地计时器 API?

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"

这会在循环中打印 0(初始停止)并且不会从 while 循环中出来.

This prints 0 (initial stop) in a loop and does not come out of the while loop.

推荐答案

在 python 文档中没有提到线程计时".时钟要么是进程范围的,要么是系统范围的.特别是 time.clock 测量进程时间,而 time.time 返回系统时间.

In the python documentation there is no mention of "thread timing". Either the clocks are process-wide or system-wide. In particular time.clock measures process time while time.time returns the system time.

在 python3.3 中,timings API 被修改和改进,但我仍然看不到任何计时器可以返回单个线程所花费的处理时间.

In python3.3 the timings API was revised and improved but still, I can't see any timer that would return the process time taken by a single thread.

还要注意,即使可能,编写这样的计时器也并不容易.计时器是特定于操作系统的,因此您必须为每个操作系统编写不同版本的模块.如果您想分析特定操作,只需在没有线程的情况下启动它.当线程化时间时,它会按预期运行,或者由于操作系统而慢得多,在这种情况下,您无能为力(至少,如果您不想编写修复"补丁GIL 或安全删除它).

Also note that even if possible it's not at all easy to write such a timer. Timers are OS specific, so you would have to write a different version of the module for every OS. If you want to profile a specific action, just launch it without threads. When threaded the timing either it runs as expected, or it is a lot slower because of the OS, in which case you can't do nothing about it(at least, if you don't want to write a patch that "fixes" the GIL or removes it safely).

这篇关于如何在Python中查找线程的运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆