簡體   English   中英

在python中執行linux time命令

[英]Executing linux time command inside python

我想計算在python腳本中執行ac程序所花費的時間。 我為此使用了os.system()函數。

os.system("{ time ./test.out < inp;} > out 2> exe_time")
  • test.out是我的c可執行文件
  • inp包含c的輸入
  • 輸出存儲c程序的輸出
  • 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實現。
  • 從shell腳本帶外傳遞參數可以安全地將任意參數傳遞給正在運行的腳本,而不必擔心這些參數是否包含嘗試的shell注入攻擊。
  • 在shell腳本中重定向2>&1可以確保將test.out編寫的任何stderr與其他輸出合並,而不是與time命令的輸出混合。
  • 如果我們確實想將輸出重定向到文件,則更好的做法是從Python執行此操作,例如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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM