using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
/*当计算开销大于切换开销时*/
Stopwatch sw = Stopwatch.StartNew();
int n=10000;
Parallel.For(0, n, i =>
{
Thread.Sleep(1);
});
sw.Stop();
/*当计算开销大于切换开销时*/
Stopwatch sw1 = Stopwatch.StartNew();
for (int j = 0; j < n; j++)
{
Thread.Sleep(1);
}
sw1.Stop();
/*当计算开销小于切换开销时*/
Stopwatch sw2 = Stopwatch.StartNew();
int Index = 0;
Parallel.For(0, n, i =>
{
Index++;
});
sw2.Stop();
/*当计算开销小于切换开销时*/
Stopwatch sw3 = Stopwatch.StartNew();
for (int j = 0; j < n; j++)
{
Index++;
}
sw3.Stop();
Stopwatch sw4 = Stopwatch.StartNew();
Parallel.For(0, n, i =>
{
});
sw4.Stop();
Console.WriteLine(" 计算开销大于切换开销时总并行时间:"+sw.Elapsed);
Console.WriteLine(" 计算开销大于切换开销时非并行时间:" + sw1.Elapsed);
Console.WriteLine(" 计算开销小于切换开销时总并行时间:" + sw2.Elapsed);
Console.WriteLine(" 计算开销小于切换开销时非并行时间:" + sw3.Elapsed);
Console.WriteLine(" 估算纯切换时间:" + sw4.Elapsed);
}
}
}
![]()