pa4*_*080 9 command-line regex grep
当grep或sed与选项一起使用--extended-regexp并且模式{1,9999}是所使用的正则表达式的一部分时,这些命令的性能会变低。为了更清楚,下面应用了一些测试。[1] [2]
grep -E、egrep和的相对性能sed -E几乎相等,因此只grep -E提供了与进行的测试。测试 1
$ time grep -E '[0-9]{1,99}' < /dev/null
real 0m0.002s
Run Code Online (Sandbox Code Playgroud)
测试 2
$ time grep -E '[0-9]{1,9999}' < /dev/null
> real 0m0.494s
Run Code Online (Sandbox Code Playgroud)
测试 3
$ time grep -E '[0123456789]{1,9999}' < /dev/null
> 真正的 21m43.947s
测试 4
$ time grep -E '[0123456789]+' < /dev/null
$ time grep -E '[0123456789]*' < /dev/null
$ time grep -E '[0123456789]{1,}' < /dev/null
$ time grep -P '[0123456789]{1,9999}' < /dev/null
real 0m0.002s
Run Code Online (Sandbox Code Playgroud)
造成这种性能显着差异的原因是什么?
Sté*_*las 10
请注意,需要时间的不是匹配,而是 RE 的构建。你会发现它也使用了相当多的 RAM:
$ valgrind grep -Eo '[0-9]{1,9999}' < /dev/null
==6518== HEAP SUMMARY:
==6518== in use at exit: 1,603,530,656 bytes in 60,013 blocks
==6518== total heap usage: 123,613 allocs, 63,600 frees, 1,612,381,621 bytes allocated
$ valgrind grep -Eo '[0-9]{1,99}' < /dev/null
==6578== in use at exit: 242,028 bytes in 613 blocks
==6578== total heap usage: 1,459 allocs, 846 frees, 362,387 bytes allocated
$ valgrind grep -Eo '[0-9]{1,999}' < /dev/null
==6594== HEAP SUMMARY:
==6594== in use at exit: 16,429,496 bytes in 6,013 blocks
==6594== total heap usage: 12,586 allocs, 6,573 frees, 17,378,572 bytes allocated
Run Code Online (Sandbox Code Playgroud)
alloc 的数量似乎与迭代次数大致成正比,但分配的内存似乎呈指数增长。
这取决于 GNU 正则表达式的实现方式。如果GNU编译grep用CPPFLAGS=-DDEBUG ./configure && make,并运行这些命令,你会看到在行动的指数效应。比这更深入意味着要了解很多关于 DFA 的理论并深入研究 gnulib regexp 实现。
在这里,您可以使用似乎没有相同问题的 PCRE:(grep -Po '[0-9]{1,65535}'最大值,尽管您始终可以执行[0-9](?:[0-9]{0,10000}){100}1 到 1,000,001 次重复之类的操作)不会比grep -Po '[0-9]{1,2}'.