Parallel Extensions をようやく使ってみた

ufcpp2007-12-19

Microsoft Parallel Extensions to .NET Framework 3.5 CTP をようやくインストール。要するに、Visual Studio 2008 をようやくβ2から RTM にインストールしなおしたんですけども。

「並列化するだけなら簡単で、並列化でパフォーマンスをあげるのが難しい」ってのを再認識しただけだったり。手元にあるソースで、AsParalle() つけたり for を Parallel.For に書き換えるだけで並列化できそうなものを何個か見繕ってやってみた結果、Core 2 Duo ごときではスピード3割増しになればいい方。

↓くらい、メモリアクセスのないものならきっちり2倍近い性能でるんですけど。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

class Program
{
	static void Main(string[] args)
	{
		Action action = () =>
		{
			double x = 6 / Math.Sqrt(3);
			double y = 3;
			for (int i = 0; i < 1 << 24; ++i)
			{
				x = 2 * x * y / (x + y);
				y = Math.Sqrt(x * y);
			}
			Console.Write("{0}: {1}, {2}\n",
				Thread.CurrentThread.ManagedThreadId, x, y);
		};

		var sw = new System.Diagnostics.Stopwatch();

		sw.Reset(); sw.Start();
		Parallel.Do(
			action, action, action, action,
			action, action, action, action
		);
		sw.Stop();
		Console.Write("par {0}\n", sw.ElapsedMilliseconds);

		sw.Reset(); sw.Start();
		action(); action(); action(); action();
		action(); action(); action(); action();
		sw.Stop();
		Console.Write("seq {0}\n", sw.ElapsedMilliseconds);
	}
}

ちなみに、今日の添付の画像は、「8 Core マシンでやってみた」の図(タスクマネージャのスクリーンコピー)。↑みたいなプログラムならきっちり8倍の性能でますけど、たいていはメモリアクセスがネックで CPU 使用率7割くらいまでしかいかないっぽい。