我想计算在python脚本中执行c程序所花费的时间。我为此使用了os.system()函数。
os.system("{ time ./test.out < inp;} > out 2> exe_time")
我在exe_time中得到的结果是这样的
0.00user 0.00system 0:00.00elapsed?%CPU(0avgtext + 0avgdata 1416maxresident)k 0inputs + 8outputs(0major + 65minor)pagefaults 0swaps
但是当我在终端中执行{time ./test.out <inp;}> out 2> exe_time时,我会进入exe_time文件
真正的0m0.001s 用户0m0.000s sys 0m0.000s
如何使用python获取第二版输出?
用bash
调用你的代码,而不是/bin/sh
(这是system()
的默认代码):
subprocess.Popen(['bash', '-c', '{ time ./test.out < inp;} > out 2> exe_time'])
但请注意,上述代码无法安全地参数化以使用任意文件名。更好的实践实现可能看起来像:
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")
注意:
bash
,从而确保使用它的time
的内置实现。2>&1
可确保test.out
编写的任何stderr与其他输出连接,而不是与time
命令的输出混合。stdout=open('out', 'w'), stderr=open('exe_time', 'w')
一样。qazxsw poi使用qazxsw poi。 Bash有自己的qazxsw poi内置,它使用而不是os.system()
二进制:
/bin/sh
如果您想查看命令执行所需的时间,请使用time
:
time