gpt4 book ai didi

c# - 快速迭代多维字符串数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:59 24 4
gpt4 key购买 nike

我正在尝试找出迭代多维 C# 数组的最快方法。我已经剥离了所有域代码以专注于问题。目前,它的执行时间为 1.86 秒,在这段时间内执行了大约 25,000,000 次迭代,处理了 5000 个数组元素。我为自己设定的目标是在 2 天内尽可能降低 1.86s :-)

在现实世界中,需要处理的面积更像是 50,000²。

我尝试过使用 PLINQ,但似乎线程开销实际上使它变慢了(达到 3.48 秒)。

我认为不安全的 C# 可能是可行的方法,但是,在我走这条路之前,我会很感激任何关于如何提高性能的想法?我以前没有做过不安全的 C#,所以我不确定这是否会提高性能?!

Console.WriteLine("started");
var sw = System.Diagnostics.Stopwatch.StartNew();
long iterations = 0;
string[] data = new string[5000];
string[] data2 = new string[5000];
string[] data3 = new string[5000];

int ubound = data.GetUpperBound(0);
for (int i = 0; i <= ubound; i++)
{
string d1 = data[i];
string d2 = data2[i];
string d3 = data3[i];

for (int j = 0; j < ubound; j++)
{
string e1 = data[j];
string e2 = data2[j];
string e3 = data3[j];
Interlocked.Increment(ref iterations);
}

Interlocked.Increment(ref iterations);
}
Console.WriteLine("Finished {0} iterations in {1} seconds", iterations, sw.Elapsed.TotalSeconds);

最佳答案

代替多维数组,使用平面数组并使用数学来解决它:

Console.WriteLine("started");
var sw = System.Diagnostics.Stopwatch.StartNew();
long iterations = 0;

var width=5000;
var height=3;
string[] data = new string[width*height];
for (int i = 0; i < width; i++)
{
string d1 = data[i];
string d2 = data[width+i];
string d3 = data[width*2+i];

for (int j = 0; j < width; j++)
{
string e1 = data[j];
string e2 = data[width+j];
string e3 = data[width*2+j];
Interlocked.Increment(ref iterations);
}
//});

Interlocked.Increment(ref iterations);
}
Console.WriteLine("Finished {0} iterations in {1} seconds", iterations, sw.Elapsed.TotalSeconds);

关于c# - 快速迭代多维字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11891788/

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