Skip to content

Instantly share code, notes, and snippets.

@geoff-m
Created April 7, 2023 03:03
Show Gist options
  • Save geoff-m/a458d146ac654e662bdfb3451e25e0b3 to your computer and use it in GitHub Desktop.
Save geoff-m/a458d146ac654e662bdfb3451e25e0b3 to your computer and use it in GitHub Desktop.
Simple demo of Parallel LINQ
Parallel took: 00:00:00.4485898
Sequential took: 00:00:11.0775119
Parallel speedup: 24.69x
using System.Diagnostics;
namespace test_thread;
class Program
{
static void Main()
{
var p = new Program();
var goal = 100;
var parallelTime = p.TimeParallel(Integers(), goal);
Console.WriteLine($"Parallel took: {parallelTime}");
var sequentialTime = p.TimeSequential(Integers(), goal);
Console.WriteLine($"Sequential took: {sequentialTime}");
var speedup = sequentialTime / parallelTime;
Console.WriteLine($"Parallel speedup: {speedup:F2}x");
}
private TimeSpan TimeParallel(IEnumerable<int> inputData, int goal)
{
var mappedValues = inputData
.AsParallel()
.Select(SlowFunction);
var sw = Stopwatch.StartNew();
var found = mappedValues.Contains(goal);
sw.Stop();
Debug.Assert(found);
return sw.Elapsed;
}
private TimeSpan TimeSequential(IEnumerable<int> inputData, int goal)
{
var mappedValues = inputData
.Select(SlowFunction);
var sw = Stopwatch.StartNew();
var found = mappedValues.Contains(goal);
sw.Stop();
Debug.Assert(found);
return sw.Elapsed;
}
private static IEnumerable<int> Integers()
{
for (var i = 0; true; ++i)
yield return i;
}
private static T SlowFunction<T>(T value)
{
Thread.Sleep(100);
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment