我是 C# 的新手,我需要一些帮助来优化我的代码。
struct Data { public static int numberOfPixels; public static string[] filePaths; public static string[] fileNames; public static double[] z; public static int numberOfFrames; public static byte[][] imageBuffer; public static int bufferSize = 1000; public static double[] num; public static double[] den; } public class Methods { public void RetrieveFileList() { Console.WriteLine("Please enter the folder path where all measurement files are stored: "); Data.filePaths = Directory.GetFiles(Console.ReadLine(),"*.bin"); Data.fileNames = new string[Data.filePaths.Length]; Data.numberOfFrames = Data.filePaths.Length; Data.z = new double[Data.filePaths.Length]; int n = 0; foreach(string file in Data.filePaths) { Data.fileNames[n] = Path.GetFileNameWithoutExtension(file); n++; } } public void CreatePositionArray() { Console.WriteLine("Please enter the stepsize used during the scan in nanometers: "); double stepsize = Convert.ToDouble(Console.ReadLine()); int n = 0; foreach(string file in Data.fileNames) { Data.z[n] = Convert.ToInt32(file) * stepsize / 1000; n++; } } public void InitializeBufferArray() { Data.imageBuffer = new byte[Data.numberOfFrames][]; } public byte[] ReadBinaryFile(int index) { return File.ReadAllBytes(Data.filePaths[index]); ; } public void FillImageBuffer() { for (int i = 0; i < Data.bufferSize; i++) { Data.imageBuffer[i] = ReadBinaryFile(i); } Data.numberOfPixels = Data.imageBuffer[0].Length; Data.num = new double[Data.numberOfPixels]; Data.den = new double[Data.numberOfPixels]; } } class Program { static void Main(string[] args) { Method.RetrieveFileList(); Method.CreatePositionArray(); Method.InitializeBufferArray(); Method.FillImageBuffer(); for(int i = 0; i < Data.numberOfFrames; i++) { for (int j = 0; j < Data.numberOfPixels; j++) { double der = Math.Pow(Data.imageBuffer[i+1][j] - Data.imageBuffer[i][j], 2); if (der < 1) der = 0; Data.num[j] = Data.num[j] + Data.z[i] * der; Data.den[j] = Data.den[j] + der; } } } }
特别是我的 Main 方法中的两个循环。现在这个循环处理大约 1000 帧,每帧 1210000 像素。外层循环的一次迭代执行大约需要 80 毫秒。 到这里最好的方法是什么? 创建多个线程并将我的缓冲区拆分为预定义的垃圾或使用 Parallel 类? 我将不胜感激任何形式的帮助。
谢谢。
最佳答案
您可能需要反转循环顺序以减少数组索引引用。此外,最好不要使用 Math.Pow(der, 2),而是使用 der*der - 它会更快一些
Method.RetrieveFileList();
Method.CreatePositionArray();
Method.InitializeBufferArray();
Method.FillImageBuffer();
for (int j = 0; j < Data.numberOfPixels; j++) {
double num = 0
double den = 0;
for(int i = 0; i < Data.numberOfFrames; i++) {
double der = Data.imageBuffer[i+1][j] - Data.imageBuffer[i][j]
if ((der *= der) < 1) der = 0;
num += Data.z[i] * der;
den += der;
}
Data.num[j] = num;
Data.den[j] = den;
}
老实说,我认为它不会显着提高性能。
关于c# - 优化double for循环以提高执行速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40943868/