Parallel Extensions to the .NET FX CTP

早速遊んでますが,粒度を小さくしすぎるとかえって遅くなったりと難しいですのぅ.

を参考にソートでも.

class Program
{
    static IEnumerable<int> RandomSequence()
    {
        var rand = new Random();
        while (true)
        {
            yield return rand.Next();
        }
    }
    static void Main(string[] args)
    {
        var array1 = RandomSequence().Take(1024 * 1024 * 16).ToArray();
        var array2 = array1.Clone() as int[];

        var sw = new Stopwatch();
        sw.Start();
        PFXUtil.ParQuickSort(array1, 0, array1.Length - 1);
        sw.Stop();
        var score1 = sw.ElapsedMilliseconds;

        sw.Start();
        PFXUtil.SeqQuickSort(array2, 0, array2.Length - 1);
        sw.Stop();
        var score2 = sw.ElapsedMilliseconds;

        var check = Enumerable.SequenceEqual(array1, array2);

        Console.WriteLine("Parallel {0} ms, Sequential {1} ms, check {2}",
            score1, score2, check ? "OK" : "Failed");
    }
}

とりあえず INSERTION_THRESHOLD = 16, SEQUENTIAL_THRESHOLD = 2048 ぐらいで実験.

Parallel 4492 ms, Sequencial 12290 ms, check OK

ちなみに自前で Partition とかの実装をしたくない人は以下に C# と Visual Basic の完全なサンプルコードがあります.私は気付かず書いちゃいましたけど.

C:\Program Files\Microsoft Parallel Extensions Dec07 CTP\Samples\TaskParallelLibrary\TaskParallelLibraryExamples

ちなみにこのフォルダにあるサンプルプログラムは 5 通りのテストを行うのですが,最後の Search example はデスクトップ上のファイルに再帰的に grep をかけていくというものなのでご注意を.というか GB 単位の ISO イメージが何個も転がっているところでそんなことされると死にます,みたいな.
最初の 4 つのテスト結果はこんな感じでした.

// Intel Core Duo T2500 @ 2.00GHz (2 Virtual CPUs)
NQueen speedup: 9.21x
Multiplication speedup: 1.58x
Sorting speedup: 1.66x
Summing speedup: 1.79x

// Intel Xeon (Prestonia) @ 2.00GHz x 2 (4 Virtual CPUs)
NQueen speedup: 5.16x
Multiplication speedup: 1.86x
Sorting speedup: 2.06x
Summing speedup: 2.16x

メモ

  • System.Linq.ParallelQuery.AsParallel<T> が返すのは IParrallelEnumerable<T>
    • IParrallelEnumerable<T> は IQueryable<T> ではない.
    • Expression Trees を食う並列計算コンテナの道は遠い,のかも.
  • System.Linq.ParallelQuery.PrallelEnumerable に ZipWith という internal method がある.
  • Parallel Programming with .NET: Known Correctness Bugs with the Parallel Extensions CTP December 2007
  • System.Threading.Tasks.TaskmanagerPolicy.IdealThreads ってのがある.Xbox 360 みたいな環境で動かすときに使うかも.