Created
October 16, 2023 23:26
-
-
Save neon-sunset/19cfbafdae1429cf4a8dc9d7f6c6c7da to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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