計時來源指令的執行

計時來源指令的執行

我正在嘗試改進 zsh 點檔案的執行,並且我需要計算子腳本的執行時間。我的程式碼中有一段.zshrc看起來像這樣:

typeset -U config_files
config_files=($DOTFILES/**/*.zsh)
for file in  ${(M)config_files}
do
    source file
done

我想做的是這樣的:

for file in  ${(M)config_files}
do
    \time -f %E source file
done

但不幸的是,我得到了這樣的回應:

time: cannot run source: No such file or directory

我哪裡錯了?

答案1

source是內建指令,而不是外部指令,因此使用外部time來計時是沒有意義的。執行下列任一操作:

TIMEFMT=%E
for file in  ${(M)config_files}
do
    time (source file)
done

或者:

for file in  ${(M)config_files}
do
    \time -f %E zsh -c 'source "$1"' zsh "$file"
done

在前者中,子 shell 是必要的,因為:

附加說明:應用於目前 shell 中執行的任何構造的內建時間將被靜默忽略。因此,雖然在語法上可以在 time 關鍵字之後立即放置一個開頭花句或重複循環等,但您將無法獲得計時統計資料。您必須使用括號來強制執行子 shell,然後對其進行計時。

在後一種情況下,您將為每個檔案啟動一個新的 zsh 實例。因此,在這兩種情況下,都無法輕鬆地對依賴腳本進行計時(即,一個設定檔執行另一個設定檔所需的操作或以某種方式影響另一個設定檔)。或者,您可以保存每個來源之後的輸出time,這將為您提供累積計時:

TIMEFMT=%E
{time} 2> times
for file in  ${(M)config_files}
do
    source file
    {time} 2>> times
done

然後你可以使用awk或 來取得單獨的計時:

awk 'NR != 1 {print $0 - prev} {prev = $0; getline}' times

答案2

我查看了man time命令並注意到

Users of the bash shell need to use an explicit path in order to run
the external time command and not the shell builtin variant.  On system
where time is installed in /usr/bin, the first example would become

所以我猜你應該提供一條時間路徑。請注意我沒有 zsh 經驗

相關內容