[英]Executing linux time command inside python
我想計算在python腳本中執行ac程序所花費的時間。 我為此使用了os.system()函數。
os.system("{ time ./test.out < inp;} > out 2> exe_time")
我在exe_time中得到的結果是這樣的
0.00user 0.00系統0:00.00經過?%CPU(0avgtext + 0avgdata 1416maxresident)k 0輸入+ 8輸出(0major + 65minor)頁面錯誤0交換
但是當我在終端執行{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')
。 os.system()
使用/bin/sh
。 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
如果要查看執行命令需要多長時間,只需使用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.