matlab - 为什么 MATLAB 的逐元素求幂会加速 512 个元素?

标签 matlab exponentiation

当数组的大小变为 512 时,MATLAB 的幂函数计算常量基数和指数数组的逐元素指数变得明显更快。我预计计算时间会随着输入大小的增加而增加,但是,有当指数数组中有 512 个元素时明显下降。这是一个示例代码

x_list = 510:514;
for i = 1:numel(x_list)
    x = x_list(i);
    tic
    for j = 1:10000
        y = power(2,1:x); 
    end
    toc
end

代码的输出是

Elapsed time is 0.397649 seconds.
Elapsed time is 0.403687 seconds.
Elapsed time is 0.318293 seconds.
Elapsed time is 0.238875 seconds.
Elapsed time is 0.175525 seconds.

这里发生了什么?

image

最佳答案

我看到使用随机数作为指数的效果与我使用 1:n 范围内的整数看到的效果相同:

x = 500:540;
t = zeros(size(x));
for ii = 1:numel(x)
    %m = 1:x(ii);
    m = 500*rand(1,x(ii));
    t(ii) = timeit(@()power(2,m));
end
plot(x,t)

graph showing jump down in execution time around 512

当强制 MATLAB 使用带有 maxNumCompThreads(1) 的单线程并再次运行上面的代码时,我看到了这个图表(注意 y 轴,峰值只是噪音):

graph not showing the jump at 512

在我看来,MATLAB 使用单个内核来计算 511 个值的指数,如果矩阵较大,则启动所有内核。使用多线程会产生开销,对于小数组不值得这样做。开销与时间节省平衡的确切点取决于许多因素,因此硬编码何时切换到多线程计算的固定阈值会导致在具有不同特征的系统上执行时间的跳跃阈值确定。

注意 @norok2 没有看到同样的跳跃,因为在他们的系统上 MATLAB was limited to a single thread .

关于matlab - 为什么 MATLAB 的逐元素求幂会加速 512 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56972394/

相关文章:

matlab - 正态概率图解释

matlab - matrix(256*256) 的行列式可能是无限的

matlab - 括号中的波浪字符

c++ - C++ 中的模幂运算

带有神秘附加字符的 Javascript Date getTime() 代码片段

matlab - 通过用一个 2D 矩阵索引另一个 2D 矩阵来矢量化创建 3D 矩阵

python - 在 plotly 中触发音频悬停效果

haskell - 在 Haskell 中使用带有列表列表的 map 时出现问题

c++ - 指数的前 n 位

c - 将矩阵提升为复数幂