c#-优化对数组中的每个元素进行平方或乘法

我有两个问题想问.

>第一个是有一个hf = {1,4,9,……..,n-1,n}的数组.我想对数组中的每个元素求平方,如{1 ^ 2,4 ^ 2,9 ^ 2,……..,(n-1)^ 2,n ^ 2}.
>有两个数组.一个是hf = {1,4,9,…,n-1,n},另一个是随机= {2,3,4,……..,k- 1,k}.我想将每个分量乘以两个数组. {1 * 2,4 * 3,9 * 4,…….,(n-1)(k-1),nk}.

我为此使用的实际代码如下:

    int np = 20000;
    for (int i = 0; i < np; i++)
    {
       random[i] = randomNG.GetNormal();

       for (int j = 0; j < np; j++)
       {
           sigma[j] = Math.Pow(hf[j], 2);
           hf[j] = hf[j] * random[i];
           sigma_super[j] = sigma_super[j] + sigma[j];
           hf_super[j] = hf_super[j] + hf[j];
       } 
    }

为此,我使用了“ for”语句.问题是处理需要很多时间,因为另一个for语句中有for语句(20000×20000次迭代).

当我测量经过的时间时,大约是14秒.还有其他方法可以在更短的时间内做同样的事情(也许使用开源库中的矩阵类)吗?我真的很想优化这个过程.

解决方法:

20,000个元素的两个数组(总共40,000个元素)并不多.您如何实现代码以使其花费“大量时间”?

这样处理很快:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        int[] array1 = new int[20000];
        int[] array2 = new int[20000];
        int[] square = new int[20000];
        int[] product = new int[20000];

        Random r = new Random();
        for (int i = 0; i < array1.Length; i++)
        {
            array1[i] = r.Next(1, 10);
            array2[i] = r.Next(1, 10);

            square[i] = array1[i] * array1[i];
            product[i] = array1[i] * array2[i];
        }

        // Only displaying the first 20 results
        Console.WriteLine("Array1 : {0}", String.Join(",", array1.Take(20)));
        Console.WriteLine("Array2 : {0}", String.Join(",", array2.Take(20)));
        Console.WriteLine("Square : {0}", String.Join(",", square.Take(20)));
        Console.WriteLine("Product: {0}", String.Join(",", product.Take(20)));
    }
}

结果(每次执行都会有所不同):

Array1 : 4,3,4,7,3,3,5,6,3,3,9,7,5,4,4,2,8,7,4,7
Array2 : 4,7,6,7,4,6,4,8,8,3,7,2,2,7,3,2,4,2,8,3
Square : 16,9,16,49,9,9,25,36,9,9,81,49,25,16,16,4,64,49,16,49
Product: 16,21,24,49,12,18,20,48,24,9,63,14,10,28,12,4,32,14,32,21

在这里查看工作示例… https://dotnetfiddle.net/83I3B0

上一篇:python列表理解的评估


下一篇:如何优化此mysql查询?我使用IN()运算符