捕获在shell脚本中执行的python脚本的运行时间

问题描述:

我有bash shell脚本,它在内部调用python脚本。我想知道python执行多长时间。我不允许在python脚本中进行更改。 任何线索将提前感谢提前。捕获在shell脚本中执行的python脚本的运行时间

您可以使用time命令来获取python脚本的运行时。

]$ cat time_test.bash 
#!/bin/bash 

# You can use: time python script.py 
time python -c 'import os;os.getenv("HOME")' 

输出会是这样的

]$ ./time_test.bash 

real 0m0.010s 
user 0m0.005s 
sys 0m0.005s 
+0

我会试试这个代码只是想知道。有办法我可以存储执行时间值的变量? – MrAdfire

这可能是值得探讨这个问题:How to get execution time of a script effectively?

本质上讲,你有几种选择:

时间整个脚本(bash或python)从终端(或您的bash脚本)

time shell_script.sh   #this 
time python some_program.py #or maybe this 

或者如果time不适用于您,您可以在bash脚本中遵循此模式计时代码,该代码还会返回运行时的简洁变量。

start=`date +%s` 
python some_program.py 
end=`date +%s` 

runtime=$((end-start)) 
+0

这会给出执行bash脚本的时间,而不是python脚本。 – iamauser

+0

谢谢,我修正了它以表明我的意思,但还留下了原始示例。 – Peri461

/usr/bin/time script调用python脚本。这使您可以跟踪脚本的CPU和挂钟时间。

+0

这会给出执行bash脚本的时间,而不是python脚本。 – iamauser

+0

是的,它会告诉我们shell脚本所花费的时间,而不是由内部调用的python脚本所花费的时间。 – MrAdfire