performance - 优化 MATLAB 代码

标签 performance matlab vectorization

此代码运行时间极长(超过 10 分钟)。有什么方法可以优化它,使其在一分钟内完成吗?

clear all;
for i = 1:1000000
    harmonicsum = 0;
    lhs = 0;
    for j = 1:i
        % compute harmonic sum
        harmonicsum = harmonicsum + 1/j;
        % find sum of factors
        if (mod(i,j)==0)
            lhs = lhs + j;
        end
    end
    %define right hand side (rhs) of Riemann Hypothesis
    rhs = harmonicsum + log(harmonicsum) * exp(harmonicsum);

    if lhs > rhs
        disp('Hypothesis violated')
    end
end

最佳答案

@b3 has a great vectorization of rhs.

不过有一个错字,需要使用 times 而不是 mtimes:

harmonicsum = cumsum(1 ./ (1:1e6));
rhs = harmonicsum + log(harmonicsum) .* exp(harmonicsum);

对于 lhs,我建议如下,大致基于 Eratosthenes 的筛法:

lhs = 1 + [1:1e6];
lhs(1) = 1;
for iii = 2:numel(lhs)/2
    lhs(2*iii:iii:end) = lhs(2*iii:iii:end) + iii;
end;

执行时间仅为 2.45 秒(对于这一半的问题)。包括计算 rhsfind 在内的总时间不到 3 秒。

我目前正在运行另一个版本以确保结果相同。


编辑:发现了 lhs(1) 的错误并对其进行了特殊处理(这是一种特殊情况,唯一的自然数,其中 1 和 N 不是不同的因子)

关于performance - 优化 MATLAB 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7640010/

相关文章:

Eclipse Neon 慢得可怜

python-3.x - 有没有更快的方法来查找中间带有通配符的字典键?

java - 在应用程序服务器的生产中使用 Google Guice 的正确阶段是什么?

MATLAB:无法从 sym 转换为逻辑值

MATLAB 快速(按分量)矢量运算......非常快

Linux 服务器性能分析和负载监控软件

matlab - 这个素数符号有什么作用 - MATLAB?

matlab - 替换矩阵中的所有数字

r - 向量化插入元素

python - 字典值的平均值,其中值采用列表/数组的形式。 (一类)