Disappointing performance with Parallel.For

前端 未结 4 814
天涯浪人
天涯浪人 2021-02-05 08:25

I am trying to speed up my calculation times by using Parallel.For. I have an Intel Core i7 Q840 CPU with 8 cores, but I only manage to get a performance ratio of 4

4条回答
  •  太阳男子
    2021-02-05 08:48

    I think the computation gain is so low because your code is "too easy" to work on other task each iteration - because parallel.for just create new task in each iteration, so this will take time to service them in threads. I will it like this:

    int[] nums = Enumerable.Range(0, 1000000).ToArray();
    long total = 0;
    
    Parallel.ForEach(
        Partitioner.Create(0, nums.Length),
        () => 0,
        (part, loopState, partSum) =>
        {
            for (int i = part.Item1; i < part.Item2; i++)
            {
                partSum += nums[i];
            }
            return partSum;
        },
        (partSum) =>
        {
            Interlocked.Add(ref total, partSum);
        }
    );
    

    Partitioner will create optimal part of job for each task, there will be less time for service task with threads. If you can, please benchmark this solution and tell us if it get better speed up.

提交回复
热议问题