使用命令生成的一行echo {,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}
包含 8191 个单词,即 114687 个字符:106497 个点和 8190 个空格。
为什么将其拆分| xargs -n 1
需要计算时间?在我的电脑上是 8 秒。
背景故事。
与 bash 大括号扩展开玩笑,我偶然发现了一个奇特的问题。我正在检查示例问题中 bash 大括号扩展的时间:在新行中打印一、二等最多“n”(= 13)个点的字符串,避免显式循环和变量。我想出了这个有点慢的解决方案:
$ time echo {,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·} | xargs -n 1 | sort -u
·
··
···
····
·····
······
·······
········
·········
··········
···········
············
·············
real 0m8.800s
user 0m0.188s
sys 0m0.748s
我认为这是由性能引起的sort
,所以我检查了一个没有排序的解决方案:
$ time echo {,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·} | xargs -n 1 | awk '{if (!a[$0]) {print $0} ; a[$0]=$0}'
·
··
···
····
·····
······
·······
········
·········
··········
···········
············
·············
real 0m8.250s
user 0m0.152s
sys 0m0.784s
这有点快。扩张本身快得惊人:
time echo {,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·} > /dev/null
real 0m0.024s
user 0m0.020s
sys 0m0.004s
将点墙打印到控制台时为 0m0.250s,但与计算相比,该输出通常较慢。所以我检查了分割线需要多长时间:
time echo {,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·}{,·} | xargs -n 1 > /dev/null
real 0m8.551s
user 0m0.096s
sys 0m0.724s
xargs
这段时间都在做什么?
答案1
xargs 很慢,因为它运行了/bin/echo
8191 次。
代替使用| tr -s " " "\n"
。