在使用numpython的Python中使用for循环加速Python nditer

2024-09-30 14:38:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加速下面的Python代码。不确定我能做些什么来加速下面的代码

with np.nditer(cmpd_array, flags=['multi_index'], op_flags=['readwrite']) as it:
   for x in it:
      x[...] = sum(np.random.choice(SIS_Array_Norm, x))
      count += 1

enter image description here

编辑:这里是我基于Python程序的C++实现,以便更好地解释我在Python中所做的事情。C++代码稍微快一点。

std::vector<std::vector<int>> calculateMonteCarlo(std::vector<std::vector<int>> cmpdArray, std::vector<float> sisNormalized)
{
    auto newVector = std::vector<std::vector<int>>();
    auto count = 0;

    for (auto& it : cmpdArray)
    {
        auto tmpVector = std::vector<int>();

        for (int i = 0; i < it.size(); i++)
        {
            std::cout << "Monte Carlo Simulation: " << count << std::endl;

            auto poissonChoice = randomChoice(sisNormalized, it[i]);
            auto sum = vectorSum(poissonChoice);

            tmpVector.push_back(sum);
            count++;
        }

        newVector.push_back(tmpVector);
    }

    return newVector;
}

Tags: 代码forautocountnpitintflags