XML technologies / Regular expressions / The art of writing regular expressions / Benchmarking
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
This chapter concerns speed and efficiency and occasionally cites regex benchmarks. Here are basic benchmarking principles and simple programs in several languages.
Benchmarking measures code execution time: read the clock before and after, then subtract. Compare ˹^(a|b|c|d|e|f|g)+$˼ and ˹^[a-g]+$˼. Here is a Perl benchmark, not yet useful in this form:
use Time::HiRes 'time'; # time() gibt jetzt eine Fließkommazahl zurück.
$Startzeit = time();
"abababdedfg" =~ m/^(a|b|c|d|e|f|g)+$/;
$Endzeit = time();
printf("Alternation: %.3f sec.\n", $Endzeit - $Startzeit);
$Startzeit = time();
"abababdedfg" =~ m/^[a-g]+$/;
$Endzeit = time();
printf("Zeichenklasse: %.3f sec.\n", $Endzeit - $Startzeit);This simple script needs several conditions for meaningful measurements:
Time only relevant code
Measure actual work, minimizing setup and cleanup inside the timed interval. Initialize data and clean up outside it.
Run enough code
The interesting code is often shorter than the clock's measurable resolution.
Running the script on my machine gives:
Alternation: 0.000 sec. Zeichenklasse: 0.000 sec.This says little except that both finish below the clock's resolution. Repeat twice, ten times, or ten million times until measurements are precise enough. The required duration depends on the system; with hundredth-second resolution, half a second gives meaningful results.
Measure the right code
After ten million repeats, even updating the counter adds significant overhead. Minimize it to measure actual work. Longer subjects increase the amount of actual work per iteration.
Taking this into account gives:
use Time::HiRes fltimefl; # time() gibt jetzt eine Fließkommazahl zurück.
$Iterationen = 1000; # Anzahl der Iterationen.
$Teststring = "abababdedfg" x 1000; # Ergibt einen sehr langen String.
$Zaehler = $Iterationen;
$Startzeit = time();
while ($Zaehler-- > 0) {
$Teststring =~ m/^(a|b|c|d|e|f|g)+$/;
}
$Endzeit = time();
printf("Alternation: %.3f sec.\n", $Endzeit - $Startzeit);
$Zaehler = $Iterationen;
$Startzeit = time();
while ($Zaehler-- > 0) {
$Teststring =~ m/^[a-g]+$/;
}
$Endzeit = time();
printf("Zeichenklasse: %.3f sec.\n", $Endzeit - $Startzeit);Here, $Teststring and $Zaehler are initialized before timing. For $Teststring, use Perl's x operator to repeat the left string the number of times on the right. Perl 5.8 gives on my machine:
Alternation: 7.276 sec. Zeichenklasse: 0.333 sec.
The class is about 22 times faster than alternation here. Repeat benchmarks and take the shortest time to reduce background-process interference.
What is being measured?
Change initialization to:
my $Iterationen = 1000000;
my $Teststring = "abababdedfg";The subject is a thousand times shorter, with a thousand times more iterations. Work is similar, results differ:
Alternation: 18.167 sec. Zeichenklasse: 5.231 sec.
Both are slower and differ by only 3.5 times. More overhead: decrementing and testing $Zaehler and preparing the regex engine now happen a thousand times more often.
Overhead adds almost five seconds to the faster version and over ten to alternation. The difference mainly comes from repeatedly capturing unused text.
The point is that results strongly depend on the mix of actual work and overhead measured.
PHP benchmarks
Here is the PHP version:
$Iterationen = 1000;
/* Einen langen Suchtext aufsetzen */
$TestString = "";
for ($i = 0; $i < 1000; $i++)
$TestString .= "abababdedfg";
/* Erster Test mit einer Alternation */
$Startzeit = gettimeofday();
for ($i = 0; $i < $Iterationen; $i++)
preg_match('/^(a|b|c|d|e|f|g)+$/', $TestString);
$Endzeit = gettimeofday();
$sec = ($Endzeit['sec'] + $Endzeit['usec'] /1000000) -
($Startzeit['sec'] + $Startzeit['usec']/1000000);
printf("Alternation: %.3f sec.\n", $sec);
/* Zweiter Test mit einer Zeichenklasse */
$Startzeit = gettimeofday();
for ($i = 0; $i < $Iterationen; $i++)
preg_match('/^[a-g]+$/', $TestString);
$Endzeit = gettimeofday();
$sec = ($Endzeit['sec'] + $Endzeit['usec'] /1000000) -
($Startzeit['sec'] + $Startzeit['usec']/1000000);
printf("Zeichenklasse: %.3f sec.\n", $sec);On my machine:
Alternation: 27.404 sec. Zeichenklasse: 0.288 sec.
If this reports “not being safe to rely on the system’s timezone settings”, add these lines at the top:
if (phpversion() >= 5)
date_default_timezone_set("GMT");Java benchmarks
Benchmarking Java is tricky. First a naive example, then why it is naive and how to improve it.
import java.util.regex.*;
public class JavaBenchmark {
public static void main(String [] args)
{
Matcher regex1 = Pattern.compile("^(a|b|c|d|e|f|g)+$").matcher("");
Matcher regex2 = Pattern.compile("^[a-g]+$").matcher("");
long iterationen = 1000;
StringBuffer temp = new StringBuffer();
for (int i = 1000; i > 0; i--)
temp.append("abababdedfg");
String testString = temp.toString();
// Erste Regex ...
long zaehler = iterationen;
long startZeit = System.currentTimeMillis();
while (--zaehler > 0)
regex1.reset(testString).find();
double sekunden =
// Zweite Regex ... (System.currentTimeMillis() - startZeit)/1000.0;
System.out.println("Alternation: " + sekunden + " sec.");
zaehler = iterationen;
startZeit = System.currentTimeMillis();
while (--zaehler > 0
regex2.reset(testString).find();
sekunden = (System.currentTimeMillis() - startZeit)/1000.0;
System.out.println("Zeichenklasse: " + sekunden + " sec.");
}
}Regexes compile during initialization: we measure searching, not compilation.
Java speed depends on the VM. Sun's standard JRE includes a Client VM for fast startup and a Server VM optimized for long-running programs.
My Client VM results:
Alternation: 19.318 sec. Zeichenklasse: 1.685 sec.
My Server VM results:
Alternation: 12.106 sec. Zeichenklasse: 0.657 sec.
Timing depends on VM optimizations. Some use just-in-time compilers, compiling code only when needed.
Sun's VM uses what I call a better-late-than-never compiler (BLTN), invoked during execution to optimize frequently run, hot code. Long-running VMs are warmed up; our benchmarks begin cold, before optimization.
Warm the VM by placing measurements in a loop:
// Erste Regex ...
for (int i = 4; i > 0; i--)
{
long zaehler = iterationen;
long startZeit = System.currentTimeMillis();
while (--zaehler > 0)
{
regex1.reset(testString).find();
}
double sekunden = (System.currentTimeMillis() - startZeit)/1000.0;
System.out.println("Alternation: " + sekunden + " sec.");
}After enough repetitions, say ten seconds, the compiler optimizes hot code. My Server VM gives roughly 8% and 25% improvements:
Alternation: 11.151 sec. Zeichenklasse: 0.483 sec.
Garbage collection also disturbs timings; longer runs minimize its impact.
VB.NET benchmarks
Our VB.NET program:
Option Explicit On
Option Strict On
Imports System.Text.RegularExpressions
Module Benchmark
Sub Main()
Dim Regex1 as Regex = New Regex("^(a|b|c|d|e|f|g)+$")
Dim Regex2 as Regex = New Regex("^[a-g]+$")
Dim Iterationen as Integer = 1000
Dim Teststring as String = ""
Dim I as Integer
For I = 1 to 1000
Teststring = Teststring & "abababdedfg"
Next
Dim Startzeit as Double = Timer()
For I = 1 to Iterationen
Regex1.Match(Teststring)
Next
Dim Sekunden as Double = Math.Round(Timer() - Startzeit, 3)
Console.WriteLine("Alternation: " & Sekunden & " sec.")
Startzeit = Timer()
For I = 1 to Iterationen
Regex2.Match(Teststring)
Next
Sekunden = Math.Round(Timer() - Startzeit, 3)
Console.WriteLine("Zeichenklasse: " & Sekunden & " sec.")
End Sub
End ModuleOn my machine:
Alternation: 13.311 sec. Zeichenklasse: 1.680 sec.
.NET's Regex constructor accepts RegexOptions.Compiled to compile a more optimized form (see Optimized expressions with Compiled). My results:
Alternation: 5.499 sec. Zeichenklasse: 1.157 sec.
Both improve with Compiled, especially alternation, nearly threefold, versus 1.5-fold for the class. The compiler apparently optimizes alternation more.
Ruby benchmarks
The Ruby program:
Iterationen=1000
testString=""
for i in 1..1000
testString += "abababdedfg"
end
Regex1 = Regexp::new("^(a|b|c|d|e|f|g)+$");
Regex2 = Regexp::new("^[a-g]+$");
startZeit = Time.new.to_f
for i in 1..Iterationen
Regex1.match(testString)
end
print "Alternation: %.3f sec.\n" % (Time.new.to_f - startZeit);
startZeit = Time.new.to_f
for i in 1..Iterationen
Regex2.match(testString)
end
print "Zeichenklasse: %.3f sec.\n" % (Time.new.to_f - startZeit);My measured times:
Alternation: 16.311 sec. Zeichenklasse: 3.479 sec.
Python benchmarks
Our program in Python:
import re, time, fpformat
Regex1 = re.compile("^(a|b|c|d|e|f|g)+$")
Regex2 = re.compile("^[a-g]+$")
Iterationen = 1250;
Teststring = ""
for i in range(800):
Teststring += "abababdedfg"
Startzeit = time.time()
for i in range(Iterationen):
Regex1.search(Teststring)
Sekunden = time.time() - Startzeit
print "Alternation: " + fpformat.fix(Sekunden,3) + " sec."
Startzeit = time.time()
for i in range(Iterationen):
Regex2.search(Teststring)
Sekunden = time.time() - Startzeit
print "Zeichenklasse: " + fpformat.fix(Sekunden,3) + " sec."For Python, I had to shorten the subject because the original caused the runtime error “maximum recursion limit exceeded”. This acts as a pressure-relief valve when an infinite loop might occur.
I compensated with more iterations. My results:
Alternation: 10.357 sec. Zeichenklasse: 0.769 sec.
Tcl benchmarks
The same example in Tcl:
set Iterationen 1000
set Teststring ""
for {set i 1000} {$i > 0} {incr i -1} {
append Teststring "abababdedfg"
}
set Zaehler $Iterationen
set Startzeit [clock clicks -milliseconds]
for {} {$Zaehler > 0} {incr Zaehler -1} {
regexp {^(a|b|c|d|e|f|g)+$} $Teststring
}
set Endzeit [clock clicks -milliseconds]
set Sekunden [expr ($Endzeit - $Startzeit)/1000.0]
puts [format "Alternation: %.3f sec." $Sekunden]
set Zaehler $Iterationen
set Startzeit [clock clicks -milliseconds]
for {} {$Zaehler > 0} {incr Zaehler -1} {
regexp {^[a-g]+$} $Teststring
}
set Endzeit [clock clicks -milliseconds]
set Sekunden [expr ($Endzeit - $Startzeit)/1000.0]
puts [format "Zeichenklasse: %.3f sec." $Sekunden]My measured results:
Alternation: 0.362 sec. Zeichenklasse: 0.352 sec.
Almost identical speed! Recall the table Programs and their regex engine types: Tcl's hybrid NFA/DFA treats these regexes as identical. Most of this chapter does not apply to Tcl; see also DFAs, Tcl, and regex tuning.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln