解决方案
使用绝对路径
/usr/bin/time
而不是直接使用 time
命令。
问题描述
有时候需要用 time 命令统计一下命令的耗时与占用,例如:
time curl https://www.csdn.net > /dev/null
➜ ~ time curl https://www.csdn.net > /dev/null
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1149k 100 1149k 0 0 1052k 0 0:00:01 0:00:01 --:--:-- 1052k
curl https://www.csdn.net > /dev/null 0.01s user 0.01s system 1% cpu 1.101 total
如果有统计或其他用途,需要格式化 time 的输出结果,通过 man time 了解一下怎么格式化:
只需要实际时间,于是在 time 命令后加上了参数 -f '%e'
➜ ~ time -f '%e' curl https://www.csdn.net > /dev/null
zsh: command not found: -f
-f '%e' curl https://www.csdn.net > /dev/null 0.00s user 0.00s system 73% cpu 0.001 total
执行后发现,追加在 time 后面的参数 -f
被当作命令尝试执行了,当然这个命令不存在。
再仔细看看 man time 里面的内容:
对于 bash 等 Shell(例如本文的 zsh),需要使用绝对路径指定 time 命令。
通过 which 命令可以看到 time 是 shell 的保留字。
➜ ~ which time
time: shell reserved word
使用正确的方式重新执行:
➜ ~ /usr/bin/time -f '%e' curl --no-progress-meter https://www.csdn.net > /dev/null
1.25
输出了格式化后的结果。