[英]Executing linux time command inside python
I want to calculate the time taken to execute ac program inside a python script. 我想计算在python脚本中执行ac程序所花费的时间。 I used os.system() function for this.
我为此使用了os.system()函数。
os.system("{ time ./test.out < inp;} > out 2> exe_time")
The result I get in exe_time is something like this 我在exe_time中得到的结果是这样的
0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 1416maxresident)k 0inputs+8outputs (0major+65minor)pagefaults 0swaps
0.00user 0.00系统0:00.00经过?%CPU(0avgtext + 0avgdata 1416maxresident)k 0输入+ 8输出(0major + 65minor)页面错误0交换
But when I execute { time ./test.out < inp;} > out 2> exe_time in terminal I get in the exe_time file 但是当我在终端执行{time ./test.out <inp;}> out 2> exe_time时,我进入了exe_time文件
real 0m0.001s
真实的0m0.001s
user 0m0.000s用户0m0.000s
sys 0m0.000ssys 0m0.000s
How do I get the second version of output by using python? 如何使用python获取输出的第二版本?
Invoke your code with bash
, not /bin/sh
(as is default for system()
): 使用
bash
而不是/bin/sh
调用代码(这是system()
默认设置):
subprocess.Popen(['bash', '-c', '{ time ./test.out < inp;} > out 2> exe_time'])
Note however that the above code is not safe to parameterize to work with arbitrary filenames. 但是请注意,上述代码无法安全地参数化以使用任意文件名。 A better-practices implementation might instead look like:
更好的做法可能是:
o, e = subprocess.Popen(['bash', '-c', 'time "$@" 2>&1', '_', './test.out'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print("Output from command is:")
sys.stdout.write(o + "\n")
print("Output from time is:")
sys.stdout.write(e + "\n")
Note: 注意:
bash
, and thus ensuring that its built-implementation of time
is used. bash
,从而确保使用其内置的time
实现。 2>&1
within the shell script ensures that any stderr written by test.out
is joined with other output, not mixed in with the output from the time
command. 2>&1
可以确保将test.out
编写的任何stderr与其他输出合并,而不是与time
命令的输出混合。 stdout=open('out', 'w'), stderr=open('exe_time', 'w')
. stdout=open('out', 'w'), stderr=open('exe_time', 'w')
。 os.system()
uses /bin/sh
. os.system()
使用/bin/sh
。 Bash has its own time
builtin that it uses instead of the time
binary: Bash有自己的内置
time
,而不是time
二进制文件:
$ /usr/bin/time ls /asd
ls: /asd: No such file or directory
0.00 real 0.00 user 0.00 sys
$ time ls /asd
ls: /asd: No such file or directory
real 0m0.018s
user 0m0.008s
sys 0m0.013s
If you want to see how long it takes for a command to be executed, just use subprocess
: 如果要查看执行命令需要多长时间,只需使用
subprocess
:
import time
import subprocess
with open('inp', 'rb') as input_file:
with open('out', 'wb') as output_file:
start = time.time()
subprocess.call(['./test.out'], stdin=input_file, stdout=output_file)
runtime = time.time() - start
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.