Created
April 29, 2019 06:36
-
-
Save mirasrael/30af940742c760853f716c99a2872acc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void Benchmark() | |
{ | |
var iterations = 1000; | |
var size = 100000; | |
for (var i = 0; i < size; i++) | |
{ | |
concurrent.Add(i.ToString(), i); | |
simple.Add(i.ToString(), i); | |
threadSafe.Add(i.ToString(), i); | |
} | |
var sw = Stopwatch.StartNew(); | |
var max = 0; | |
for (var it = 0; it < iterations; it++) | |
{ | |
Parallel.For(0, size, i => | |
{ | |
concurrent.TryGetValue(i.ToString(), out var element); | |
if (element > max) | |
max = element; | |
}); | |
} | |
sw.Stop(); | |
Console.WriteLine($"concurrent: {sw.Elapsed}"); | |
sw = Stopwatch.StartNew(); | |
max = 0; | |
for (var it = 0; it < iterations; it++) | |
{ | |
Parallel.For(0, size, i => | |
{ | |
threadSafe.TryGetValue(i.ToString(), out var element); | |
if (element > max) | |
max = element; | |
}); | |
} | |
sw.Stop(); | |
Console.WriteLine($"thread-safe: {sw.Elapsed}"); | |
sw = Stopwatch.StartNew(); | |
var rw = new ReaderWriterLockSlim(); | |
max = 0; | |
for (var it = 0; it < iterations; it++) | |
{ | |
Parallel.For(0, size, i => | |
{ | |
rw.EnterReadLock(); | |
try | |
{ | |
simple.TryGetValue(i.ToString(), out var element); | |
if (element > max) | |
max = element; | |
} | |
finally | |
{ | |
rw.ExitReadLock(); | |
} | |
}); | |
} | |
sw.Stop(); | |
Console.WriteLine($"rw + simple: {sw.Elapsed}"); | |
sw = Stopwatch.StartNew(); | |
max = 0; | |
for (var it = 0; it < iterations; it++) | |
{ | |
Parallel.For(0, size, i => | |
{ | |
lock (simple) | |
{ | |
simple.TryGetValue(i.ToString(), out var element); | |
if (element > max) | |
max = element; | |
} | |
}); | |
} | |
sw.Stop(); | |
Console.WriteLine($"lock + simple: {sw.Elapsed}"); | |
sw = Stopwatch.StartNew(); | |
max = 0; | |
for (var it = 0; it < iterations; it++) | |
{ | |
Parallel.For(0, size, i => | |
{ | |
simple.TryGetValue(i.ToString(), out var element); | |
if (element > max) | |
max = element; | |
}); | |
} | |
sw.Stop(); | |
Console.WriteLine($"no lock: {sw.Elapsed}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment