通常我們在bash腳本中去使用一些系統(tǒng)內(nèi)嵌的命令僧须,例如pwd
伸辟,我們會這樣寫:
pwd > /dev/null
或者這樣寫:
/bin/pwd > /dev/null
如果有興趣的話雕薪,可以在你的腳本執(zhí)行時這樣去使用:
time script1.sh
你會發(fā)現(xiàn)一些令你吃驚的輸出们妥。
這里是一個簡單的測試腳本:(script1.sh)
#!/bin/bash
while true
do
x=$((x+1))
pwd > /dev/null
if [ $x -gt 50000 ]
then
exit
fi
done
$ time script1.sh
real 0m0.629s
user 0m0.484s
sys 0m0.140s
下來我們改變腳本中的一行 pwd > /dev/null
--> /bin/pwd > /dev/null
$ time ./script1.sh
real 0m32.548s
user 0m17.849s
sys 0m15.758s
奇怪的事情發(fā)生了世落,時間花費竟然差這么多N呵Α2獭!
我們用strace
命令來看下時間究竟是花費在哪里沦零?
先看直接使用pwd
$ strace -c -o /tmp/s0.out ./script1.sh
$ head -6 /tmp/s0.out
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
41.55 0.454037 1 250008 1 fcntl
18.56 0.202819 2 100003 dup2
16.80 0.183598 1 100012 close
14.30 0.156207 3 50011 openat
再來看使用/bin/pwd
$ strace -c -o /tmp/s1.out ./script1.sh
$ head -6 /tmp/s1.out
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
79.83 12.744396 127 100002 50001 wait4
11.76 1.878193 37 50001 clone
6.03 0.962723 2 400011 rt_sigprocmask
1.56 0.248643 2 100016 rt_sigaction
從收集到的數(shù)據(jù)可以看到祭隔,在使用/bin/pwd
時大部分的時間是花費在wait4
(CPU時間)去創(chuàng)建新的進程來執(zhí)行輸出的程序。但是我們用pwd
時路操,實際上只調(diào)用了一次fcntl
去打開了一個文件句柄疾渴,然后利用dup2
(管道)來執(zhí)行輸出程序,避免了CPU的等待時間屯仗。
為什么呢搞坝?我們看下命令pwd
的type:
$ type pwd
pwd is a shell builtin
pwd
是shell內(nèi)嵌的命令,它在執(zhí)行時系統(tǒng)會選擇最優(yōu)的方式執(zhí)行魁袜。想這樣的builtin命令還有很多桩撮,可以參考man手冊:
BASH_BUILTINS(1) General Commands Manual BASH_BUILTINS(1)
NAME
bash, :, ., [, alias, bg, bind, break, builtin, caller, cd, command, compgen, complete, compopt, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, false,
fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, mapfile, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times,
trap, true, type, typeset, ulimit, umask, unalias, unset, wait - bash built-in commands, see bash(1)
OK, 所有在之后的bash腳本中,如果有申明了#!/bin/bash
峰弹,并且使用到了builtin命令店量,可以優(yōu)先考慮直接使用。再有就是在進行性能分析時strace
命令可以提供很好的幫助鞠呈。