【发布时间】:2014-06-26 13:02:19
【问题描述】:
我做了一个性能测试,结果非常令人惊讶:perl 快了 20 倍以上!
这正常吗? 它是由我的正则表达式引起的吗? egrep 比 grep 慢得多吗? ...我在当前的 cygwin 和 virtualbox 中的当前 OpenSuSE 13.1 上进行了测试。
使用 perl 的最快测试:
time zcat log.gz \
| perl -ne 'print if ($_ =~ /^\S+\s+\S+\s+(ERROR|WARNING|SEVERE)\s/ )'
| tail
2014-06-24 14:51:43,929 SEVERE ajp-0.0.0.0-8009-13 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 14:52:01,031 ERROR HFN SI ThreadPool(4)-442 CepEventUnmarshaler Unmarshaled Events Duration: 111
2014-06-24 14:52:03,556 ERROR HFN SI ThreadPool(4)-444 CepEventUnmarshaler Unmarshaled Events Duration: 52
2014-06-24 14:52:06,789 SEVERE ajp-0.0.0.0-8009-1 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 14:52:06,792 SEVERE ajp-0.0.0.0-8009-1 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 14:52:07,371 SEVERE ajp-0.0.0.0-8009-9 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 14:52:07,373 SEVERE ajp-0.0.0.0-8009-9 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 14:52:07,780 SEVERE ajp-0.0.0.0-8009-11 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 14:52:07,782 SEVERE ajp-0.0.0.0-8009-11 SessionDataUpdateManager cannot register active data when window has no name
2014-06-24 15:06:24,119 ERROR HFN SI ThreadPool(4)-443 CepEventUnmarshaler Unmarshaled Events Duration: 117
real 0m0.151s
user 0m0.062s
sys 0m0.139s
很好!
使用 egrep 进行慢得多的测试:
time zcat log.gz \
| egrep '^\S+\s+\S+\s+(ERROR|WARNING|SEVERE)\s'
| tail
...
real 0m2.454s
user 0m2.448s
sys 0m0.092s
(输出同上...)
最后甚至更慢的 grep 用不同的符号(我的第一次尝试)
time zcat log.gz \
| egrep '^[^\s]+\s+[^\s]+\s+(ERROR|WARNING|SEVERE)\s'
| tail
...
real 0m4.295s
user 0m4.272s
sys 0m0.138s
(输出同上...)
解压后的文件大小约为 2.000.000 行,解压后的文件大小为 500MBytes - 匹配的行数非常少。
我的测试版本:
- OpenSuSE 与 grep (GNU grep) 2.14
- cygwin 与 grep (GNU grep) 2.16
也许是一些带有较新 grep 版本的错误?
【问题讨论】:
-
在我自己的机器上进行测试时,grep 似乎更快:grep=
0m0.011s, perl=0m0.024s。你的文件有多大? -
有趣的是,这种重复运行平均会在大约同一时间显示它们。
-
这很难相信。我会假设仅 Perl 的开销就会将性能优势转移到 grep。我知道'|'应该是效率最低的正则表达式原子之一。也许是这个因素?