C#parallel.For循环减少执行时间

时间:2017-05-12 12:33:09

标签: c# json multithreading parallel.for

我找到了一台osrm-machine,它在我请求时返回一个json字符串。 json有一些关于2个位置的特定信息,我正在处理json并得到距离属性的值,用于构建这些位置的距离矩阵。我有超过2000个位置,这个处理大约需要4个小时。我需要通过并行性来减少执行时间,但我对这个主题非常新。这是我的工作,我该怎么做才能优化并行循环?或许你可以把我带到新的方法。感谢

 var client = new RestClient("http://127.0.0.1:5000/route/v1/table/");
            var watch = System.Diagnostics.Stopwatch.StartNew();

            //rawCount = 2500
            Parallel.For(0, rowCount, i =>
            {
                Parallel.For(0, rowCount, j =>
                {
                    //request a server with spesific lats,longs
                    var request = new RestRequest(String.Format("{0},{1};{2},{3}", le.LocationList[i].longitude, le.LocationList[i].latitude,
                                                                                                        le.LocationList[j].longitude, le.LocationList[j].latitude));

                    //reading the response and deserialize into object
                    var response = client.Execute<RootObject>(request);

                    //defining objem with the List of attributes in routes
                    var objem = response.Data.routes;

                    //this part reading all distances and durations in each response and take them into dist and dur matrixes.
                    Parallel.ForEach(objem, (o) =>
                    {
                        dist[i, j] = o.distance;
                        dur[i, j] = o.duration;
                        threads[i,j] =  Thread.CurrentThread.ManagedThreadId;
                        Thread.Sleep(10);

                    });
                });
            });

        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;

0 个答案:

没有答案