ThreadPoolExecutor 获取函数执行时间
时间: 2023-11-02 11:55:11 浏览: 44
您可以使用ThreadPoolExecutor的submit()方法来提交函数执行,并通过Future对象获取函数执行的时间。下面是一个示例代码:
```python
import time
from concurrent.futures import ThreadPoolExecutor
def my_function(arg1, arg2):
# 执行耗时操作
time.sleep(1)
return arg1 + arg2
executor = ThreadPoolExecutor()
# 提交函数执行
future = executor.submit(my_function, 3, 5)
# 获取函数执行结果,并打印执行时间
start_time = time.time()
result = future.result()
end_time = time.time()
execution_time = end_time - start_time
print("函数执行结果:", result)
print("函数执行时间:", execution_time)
```
在上述代码中,我们定义了一个`my_function()`函数,模拟一个耗时操作。然后,我们创建了一个ThreadPoolExecutor对象,并使用submit()方法提交函数执行。接下来,使用future.result()方法获取函数执行结果。同时,在函数执行前后记录了时间戳,通过计算两个时间戳之间的差值,得到了函数执行的时间。最后,我们打印出函数执行结果和执行时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)