问题描述
同时尝试了解如何使用并行性和并发性 我在比较基准列表上的登录时花费了三种方法的时间,同时对这些方法进行了基准测试 但是这三种方法现在让我非常困惑:
我问这段代码是怎么回事?
public class LookUpCollections
{
private const int N = 3;
private readonly List<int> _list;
public LookUpCollections()
{
_list = new List<int>();
for (int i = 0; i < N; i++)
{
_list.Add(i);
}
}
[Benchmark]
public void ListLookup() => _list.ForEach(x => Thread.Sleep(TimeSpan.FromSeconds(2)));
[Benchmark]
public void ListLookupAsParallel() => _list.AsParallel<int>().ForAll((x) =>
Thread.Sleep(TimeSpan.FromSeconds(2)));
[Benchmark]
public async IAsyncEnumerable<int> ListLookupAsync()
{
foreach (var item in _list)
{
Task.Delay(TimeSpan.FromSeconds(2)); // the method will complete before 2sec delay
await Task.Delay(TimeSpan.FromSeconds(2)); // some asynchronous work
yield return item;
}
}
}
或者这是控制台的副本和过去,以防图像出现问题:
BenchmarkDotNet=v0.12.1,OS=Windows 10.0.19041.450
.NET Core SDK=3.1.401
[Host] : .NET Core 2.1.21
DefaultJob : .NET Core 2.1.21
Method Mean Error StdDev
|--------------------- |--------------------:|-----------------:|-----------------:|
| ListLookup | 6,027,116,440.00 ns | 6,926,407.532 ns | 6,478,965.903 ns |
| ListLookupAsParallel | 2,008,655,313.33 ns | 5,275,609.028 ns | 4,934,807.958 ns |
| ListLookupAsync | 27.47 ns | 0.611 ns | 1.632 ns |
LookUpCollections.ListLookupAsync: Default -> 6 outliers were removed (37.39 ns..40.15 ns)
// * Legends *
Mean : Arithmetic mean of all measurements
Error : Half of 99.9% confidence interval
StdDev : Standard deviation of all measurements
1 ns : 1 Nanosecond (0.000000001 sec)
解决方法
鉴于您的评论,您对第三种方法的结果有一些疑问。我问过您如何调用该方法,因为如果这样正确调用,它会花费约6秒钟的时间:
List<int> _list;
async Task Main()
{
const int N = 3;
_list = new List<int>();
for (int i = 0; i < N; i++)
{
_list.Add(i);
}
await foreach(var i in ListLookupAsync())
{
Console.WriteLine(i);
}
}
public async IAsyncEnumerable<int> ListLookupAsync()
{
Console.WriteLine($"{DateTime.Now} - Entering ListLookupAsync");
foreach (var item in _list)
{
await Task.Delay(TimeSpan.FromSeconds(2)); // some asynchronous work
yield return item;
}
Console.WriteLine($"{DateTime.Now} - Exiting ListLookupAsync");
}
我真的怀疑你在测量错误的东西。基本上消耗IAsyncEnumerable
的种类与消耗不可等待的可枚举具有相同的效果:迭代/产量回报是顺序完成的。由于_list
包含3个消耗上面的代码的可枚举项,因此需要2秒钟的延迟3倍。
如果您想并行执行基于任务的方法 ,则可以利用Task.WhenAll
:
List<int> _list;
async Task Main()
{
const int N = 3;
_list = new List<int>();
for (int i = 0; i < N; i++)
{
_list.Add(i);
}
Console.WriteLine($"{DateTime.Now} - Before WhenAll");
await Task.WhenAll(_list.Select(TaskBased));
Console.WriteLine($"{DateTime.Now} - After WhenAll");
}
public async Task TaskBased(int index)
{
await Task.Delay(TimeSpan.FromSeconds(2)); // some asynchronous work
Console.WriteLine(index);
}
这大约需要2秒钟。
但是,无论如何,请:在对基准测试结果提出质疑之前,请务必确保您了解代码的作用,否则就有可能测量错误的事物并得出错误的结论。