gpt4 book ai didi

.net - 为什么当我使用线程时以下代码的性能会下降?

转载 作者:行者123 更新时间:2023-12-03 03:17:50 25 4
gpt4 key购买 nike

为什么当我使用线程时以下代码的性能会下降?

**1.没有线程

int[] arr =  new int[100000000]; //Array elements - [0][1][2][3]---[100000000-1]      
addWithOutThreading(arr); // Time required for this operation - 1.16 sec

addWithOutThreading 的定义

        public void addWithOutThreading(int[] arr)
{
UInt64 result = 0;
for (int i = 0; i < 100000000; i++)
{
result = result + Convert.ToUInt64(arr[i]);
}
Console.WriteLine("Addition = " + result.ToString());
}

**2.有线程

int[] arr =  new int[100000000];
int part = (100000000 / 4);
UInt64 res1 = 0, res2 = 0, res3 = 0, res4 = 0;

ThreadStart starter1 = delegate
{ addWithThreading(arr, 0, part, ref res1); };
ThreadStart starter2 = delegate
{ addWithThreading(arr, part, part * 2, ref res2); };
ThreadStart starter3 = delegate
{ addWithThreading(arr, part * 2, part * 3, ref res3); };
ThreadStart starter4 = delegate
{ addWithThreading(arr, part * 3, part * 4, ref res4); };

Thread t1 = new Thread(starter1);
Thread t2 = new Thread(starter2);
Thread t3 = new Thread(starter3);
Thread t4 = new Thread(starter4);

t1.Start();
t2.Start();
t3.Start();
t4.Start();
t1.Join();
t2.Join();
t3.Join();
t4.Join();

Console.WriteLine("Addition = "+(res1+res2+res3+res4).ToString());
// Time required for this operation - 1.30 sec

addWithThreading 的定义

public void addWithThreading(int[] arr,int startIndex, int endIndex,ref UInt64 result)
{
for (int i = startIndex; i < endIndex; i++)
{
result = result + Convert.ToUInt64(arr[i]);
}
}

最佳答案

您正在谈论一个已经相当快的操作,在创建线程以及让所有内容启动和运行方面存在性能开销。很可能是您的线程创建、数组分割以及所需的额外计算弥补了额外的时间。

关于.net - 为什么当我使用线程时以下代码的性能会下降?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2508341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com