Skip to content

Instantly share code, notes, and snippets.

@neon-sunset
Created October 16, 2023 23:26
Show Gist options
  • Save neon-sunset/19cfbafdae1429cf4a8dc9d7f6c6c7da to your computer and use it in GitHub Desktop.
Save neon-sunset/19cfbafdae1429cf4a8dc9d7f6c6c7da to your computer and use it in GitHub Desktop.
namespace System.Linq;
public static class ParallelExtensions
{
public static ParallelQuery<TResult> BatchSelect<T, TResult>(
this T[] source,
Func<Memory<T>, TResult> selector,
int degreeOfParallelism = 0)
{
return source.AsMemory().BatchSelect(selector, degreeOfParallelism);
}
public static ParallelQuery<TResult> BatchSelect<T, TResult>(
this Memory<T> source,
Func<Memory<T>, TResult> selector,
int degreeOfParallelism = 0)
{
if (degreeOfParallelism <= 0)
{
degreeOfParallelism = Environment.ProcessorCount;
}
var batchLength = source.Length / degreeOfParallelism;
return ParallelEnumerable
.Range(0, degreeOfParallelism + 1)
.Select(i =>
{
var start = i * batchLength;
var length = i == degreeOfParallelism
? source.Length - start
: batchLength;
return selector(source.Slice(start, length));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment