简体   繁体   English

如何在 Python 中获取线程执行时间

[英]How to get Thread execution time in Python

Hello I have a script that does a GET request and I need to measure the thread that is loaded with that function.您好,我有一个执行 GET 请求的脚本,我需要测量加载了该 function 的线程。 This is the code that I have written but it doesn`t show the correct time it shows 0 and sometimes 0.001 or something like that.这是我写的代码,但它没有显示正确的时间,它显示 0 有时是 0.001 或类似的东西。

import requests
import threading
import time

def functie():
    URL = "http://10.250.100.170:9082/SPVWS2/rest/listaMesaje"
    r = requests.get(url = URL)
    data = r.json()


threads = []
for i in range(5):
    start = time.clock_gettime_ns()
    t = threading.Thread(target=functie)
    threads.append(t)
    t.start()
    end = time.clock_gettime_ns()
    print(end-start)

I need an example on how to get in my code the exact thread execution time.我需要一个关于如何在我的代码中获取确切的线程执行时间的示例。 Thanks谢谢

The code in this script runs on the main thread and you are trying to measure the timing of thread t.此脚本中的代码在主线程上运行,您正在尝试测量线程 t 的时间。 To do that, you can tell main thread to wait until thread t has finished like this:为此,您可以告诉主线程等到线程 t 完成,如下所示:

import requests
import threading
import time

threads = []
start = []
end = []

def functie():
    start.append(time.clock_gettime_ns())

    URL = "http://10.250.100.170:9082/SPVWS2/rest/listaMesaje"
    r = requests.get(url = URL)
    data = r.json()

    end.append(time.clock_gettime_ns())

for i in range(5):
    start.append(time.clock_gettime_ns())
    t = threading.Thread(target=functie)
    threads.append(t)
    t.start()

for (i,t) in enumerate(threads):
    t.join()
    print(end[i]-start[i])

The other answer would produce incorrect results.另一个答案会产生不正确的结果。 If the first thread takes longer than the second, the time of the second will be recorded as the same as the first.如果第一个线程比第二个线程花费的时间长,那么第二个线程的时间将与第一个线程相同。 This is because the end times are recorded sequentially after each join finishes rather than when the thread's target function actually finishes which may be in any order.这是因为结束时间是在每次连接完成后按顺序记录的,而不是在线程的目标 function 实际完成时(可能是任何顺序)。

A better way would be to wrap the target functions of the threads with code that does this:更好的方法是使用执行此操作的代码包装线程的目标函数:

def thread_time(target):
   def wrapper(*args, **kwargs):
       st = time.time()
       try:
           return target(*args, **kwargs)
       finally:
           et = time.time()
           print(et - st)
           threading.currentThread().duration = et - st
   return wrapper

def functie():
    print "starting"
    time.sleep(1)
    print "ending"

t = threading.Thread(target=thread_time(functie))
t.start()
t.join()
print(t.duration)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM