Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Last active December 17, 2015 11:18
Show Gist options
  • Save JohanLarsson/5600702 to your computer and use it in GitHub Desktop.
Save JohanLarsson/5600702 to your computer and use it in GitHub Desktop.
[Test]
public void RegexTest()
{
var pattern = @"^(CONNECT|DELETE|HEAD|GET|OPTIONS|POST|PUT|TRACE) (\/[\S]*) HTTP\/(1.0|1.1)$";
var line = "test";
var stopWatch = Stopwatch.StartNew();
for (int i = 0; i < 2; i++)
{
stopWatch.Restart();
var m = Regex.Match(line, pattern, RegexOptions.Compiled);
Console.WriteLine("Regex.Match: " + stopWatch.GetTimeString());
}
var regex = new Regex(pattern, RegexOptions.Compiled);
stopWatch.Restart();
var n = regex.Match(line);
Console.WriteLine("regex.Match: " + stopWatch.GetTimeString());
}
Outputs:
Regex.Match: 182,2 ms
Regex.Match: 1,9 ms
regex.Match: 1,6 µs
public static class StopwatchExt
{
public static string GetTimeString(this Stopwatch stopwatch, int numberofDigits = 1)
{
double time = stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
if (time > 1)
return Math.Round(time, numberofDigits) + " s";
if (time > 1e-3)
return Math.Round(1e3 * time, numberofDigits) + " ms";
if (time > 1e-6)
return Math.Round(1e6 * time, numberofDigits) + " µs";
if (time > 1e-9)
return Math.Round(1e9 * time, numberofDigits) + " ns";
return stopwatch.ElapsedTicks + " ticks";
throw new NotImplementedException("message");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment