SIN@SAPPOROWORKSの覚書

C#を中心に、夜な夜な試行錯誤したコードの記録です。

Xamarin.Android Parallel.Foreachを回してみる

【 Xamarin 記事一覧 】

f:id:furuya02:20141130014218p:plain:w150:left

xin9leさんの所(http://xin9le.net/)では、非常に分かりやすい非同期関連のドキュメントが公開されています。
今日は、ここで紹介されていた「タスク並列ライブラリ (TPL)」のコードをAndroid(実機)で試してみました。

試したのはHTC-Jで、CPUは、MSM8660A 1.5GHz デュアルコアとなっており、予想通りというか、当たり前というか、並列で回すと約2倍の速度が出ています。

1秒のウエイトで10回ループして、通常だと10164ms、並列だと、5891ms

現状、JavaAndroidを書く場合、こんなにあっさり書けるのだろうか・・・

コードは、下記のとおりです。(xin9leさんのコード、そのまんまですw)

public class MainActivity : Activity {

        protected override void OnCreate(Bundle bundle) {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);
            var button = FindViewById<Button>(Resource.Id.MyButton);
            var textView = FindViewById<TextView>(Resource.Id.textView1);

            button.Click+= (sender, args) =>{
                var collection = new []{10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
                var sb = new StringBuffer();

                //----- 通常ループ
                var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                foreach (var item in collection){
                    sb.Append(item + "\r\n");
                    Thread.Sleep(1000);
                }
                stopwatch.Stop();
                sb.Append(stopwatch.ElapsedMilliseconds.ToString("Normal : 0[ms]\r\n"));

                //----- 並列ループ
                stopwatch.Restart();
                System.Threading.Tasks.Parallel.ForEach(collection, item => {
                    sb.Append(item + "\r\n");
                    Thread.Sleep(1000);
                });
                stopwatch.Stop();
                sb.Append(stopwatch.ElapsedMilliseconds.ToString("Parallel : 0[ms]\r\n"));

                textView.Text = sb.ToString();
            };
        }
    }

【 Xamarin 記事一覧 】