## .NET(C#) Internals: 以一个数组填充的例子初步了解.NET 4.0中的并行（一）

2010-05-11 13:11  吴秦  阅读(4226)  评论(15编辑  收藏  举报

• 通常的数组填充
• 并行的组数填充
• 性能比较

#### 1、通常的数组填充

通常的数组填充
using System;

namespace ParallelForSample
{
public class SingleCore
{
public static void Calculate(int calcVal)
{
Utility util = new Utility();
util.Start();

int[,] G = new int[calcVal, calcVal];
for (int k = 0; k < calcVal; k++)
for (int i = 0; i < calcVal; i++)
for (int j = 0; j < calcVal; j++)
G[i, j] = Math.Min(G[i, j], G[i, k] + G[k, j]);
util.Stop();

}
}
}

Utility类
public class Utility
{
private Stopwatch _stopwatch;
public void Start()
{
_stopwatch = new Stopwatch();
_stopwatch.Start();
}

public void Stop()
{
_stopwatch.Stop();
TimeSpan ts = _stopwatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("Time taken : {0}", elapsedTime);
}
}


#### 2、并行的组数填充

并行的数组填充
using System;

namespace ParallelForSample
{
public class MultiCore
{
public static void Calculate(int calcVal)
{
Utility util = new Utility();
util.Start();

int[,] G = new int[calcVal, calcVal];

Parallel.For(0, calcVal,
delegate(int k)
{
Parallel.For(0, calcVal, delegate(int i)
{
for (int j = 0; j < calcVal; j++)
G[i, j] = Math.Min(G[i, j], G[i, k] + G[k, j]);
});
}
);

util.Stop();
}
}
}

#### 3、性能比较

性能比较测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParallelForSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Single core");
SingleCore.Calculate(1000);
Console.WriteLine("Multi core");
MultiCore.Calculate(1000);
Console.WriteLine("Finished");
}
}
}