为什么我的 Matlab for 循环代码比我的矢量化版本更快

2024-01-06

我一直听说矢量化代码比 MATLAB 中的 for 循环运行得更快。然而,当我尝试向量化 MATLAB 代码时,它似乎运行得更慢。

I used tic and toc来测量时间。我只更改了程序中单个函数的实现。我的矢量化版本运行了47.228801秒,我的 for 循环版本运行了16.962089秒。

另外,在我的主程序中,我使用了大量的 N,N = 1000000数据集的大小是1 301,并且我针对具有相同大小和 N 的不同数据集运行每个版本多次。

为什么矢量化速度慢得多?如何进一步提高速度?

“矢量化”版本

function [RNGSet] = RNGAnal(N,DataSet)
%Creates a random number generated set of numbers to check accuracy overall
%   This function will produce random numbers and normalize a new Data set
%   that is derived from an old data set by multiply random numbers and
%   then dividing by N/2
randData = randint(N,length(DataSet));
tempData = repmat(DataSet,N,1);
RNGSet = randData .* tempData;
RNGSet = sum(RNGSet,1) / (N/2); % sum and normalize by the N
end

“for 循环”版本

function [RNGData] = RNGAnsys(N,Data)
%RNGAnsys This function produces statistical RNG data using a for loop
%   This function will produce RNGData that will be used to plot on another
%   plot that possesses the actual data
multData = zeros(N,length(Data));
for i = 1:length(Data)
    photAbs = randint(N,1); % Create N number of random 0's or 1's
    multData(:,i) = Data(i) * photAbs; % multiply each element in the molar data by the random numbers
end

sumData = sum(multData,1); % sum each individual energy level's data point
RNGData = (sumData/(N/2))'; % divide by n, but account for 0.5 average by n/2
end

矢量化

乍一看 for 循环代码告诉我们,因为photAbs是一个二进制数组,其每一列根据每个元素进行缩放Data,这个二进制特征可以用于矢量化。这在代码中被滥用了 -

function RNGData = RNGAnsys_vect1(N,Data)

%// Get the 2D Matrix of random ones and zeros
photAbsAll = randint(N,numel(Data));

%// Take care of multData internally by summing along the columns of the
%// binary 2D matrix and then multiply each element of it with each scalar 
%// taken from Data by performing elementwise multiplication
sumData = Data.*sum(photAbsAll,1);

%// Divide by n, but account for 0.5 average by n/2
RNGData = (sumData./(N/2))'; %//'

return;

经过分析,瓶颈似乎是随机二进制数组创建部分。因此,按照建议使用更快的随机二进制数组创建器这个智能解决方案 https://stackoverflow.com/a/25042251/3293881,上述函数可以进一步优化,如下所示 -

function RNGData = RNGAnsys_vect2(N,Data)

%// Create a random binary array and sum along the columns on the fly to
%// save on any variable space that would be required otherwise. 
%// Also perform the elementwise multiplication as discussed before.
sumData = Data.*sum(rand(N,numel(Data))<0.5,1);

%// Divide by n, but account for 0.5 average by n/2
RNGData = (sumData./(N/2))'; %//'

return;

使用智能二进制随机数组创建器,也可以优化原始代码,这将用于稍后优化 for 循环和矢量化代码之间的公平基准测试。这里列出了优化的 for 循环代码 -

function RNGData = RNGAnsys_opt1(N,Data)

multData = zeros(N,numel(Data));
for i = 1:numel(Data)

    %// Create N number of random 0's or 1's using a smart approach
    %// Then, multiply each element in the molar data by the random numbers
    multData(:,i) = Data(i) * rand(N,1)<.5; 
end

sumData = sum(multData,1); % sum each individual energy level's data point
RNGData = (sumData/(N/2))'; % divide by n, but account for 0.5 average by n/2
return;

标杆管理

基准测试代码

N = 15000; %// Kept at this value as it going out of memory with higher N's.
           %// Size of dataset is more important anyway as that decides how
           %// well is vectorized code against a for-loop code

DS_arr = [50 100 200 500 800 1500 5000]; %// Dataset sizes
timeall = zeros(2,numel(DS_arr));

for k1 = 1:numel(DS_arr)
    DS = DS_arr(k1);
    Data = rand(1,DS);

    f = @() RNGAnsys_opt1(N,Data);%// Optimized for-loop code
    timeall(1,k1) = timeit(f);
    clear f

    f = @() RNGAnsys_vect2(N,Data);%// Vectorized Code
    timeall(2,k1) = timeit(f);
    clear f
end

%// Display benchmark results
figure,hold on, grid on
plot(DS_arr,timeall(1,:),'-ro')
plot(DS_arr,timeall(2,:),'-kx')
legend('Optimized for-loop code','Vectorized code')
xlabel('Dataset size ->'),ylabel('Time(sec) ->')
avg_speedup = mean(timeall(1,:)./timeall(2,:))
title(['Average Speedup with vectorized code = ' num2str(avg_speedup) 'x'])

Results

结束语

根据我迄今为止的经验MATLAB,for 循环和向量化技术都不适合所有情况,但一切都是针对具体情况的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的 Matlab for 循环代码比我的矢量化版本更快 的相关文章

  • ElasticSearch 匹配多个前缀术语

    我试图为 ElasticSearch 提供一个包含多个术语的查询 然后给出匹配的文档 其中指定的术语位于目标字段中的任何位置 这些术语可以是完整的单词或单词前缀 示例文档 msg 你好 我是一条短信 示例查询字符串 你好消息 你好 和 消息
  • 如何提高 Field.set 的性能(也许使用 MethodHandles)?

    我正在编写一些调用的代码Field set https docs oracle com en java javase 11 docs api java base java lang reflect Field html set java l
  • cudaMalloc使用向量>进行管理 > C++ - NVIDIA CUDA

    我正在通过 NVIDIA GeForce GT 650M GPU 为我创建的模拟实现多线程 为了确保一切正常工作 我创建了一些辅助代码来测试一切是否正常 在某一时刻 我需要更新变量向量 它们都可以单独更新 这是它的要点 device int
  • isinstance(foo,types.GeneratorType)还是inspect.isgenerator(foo)?

    Python中似乎有两种方法来测试一个对象是否是生成器 import types isinstance foo types GeneratorType or import inspect inspect isgenerator foo 本着
  • MySQL InnoDB 查询性能

    我正在尝试优化一个简单的 sql 查询 该查询将多次运行大量数据 这是场景 MySQL 与 InnoDB 表 where 和 join 中使用的所有字段都已索引 表有 FK 我不需要查询的整个缓存 但每个表的缓存是可能的 表有更多的更新 插
  • 空 while 循环有什么影响?

    我知道这可能是一个有点 愚蠢 的问题 但有时 我只想循环直到条件为假 但我不喜欢让循环保持为空 所以代替 Visible true while IsRunning Visible false 我通常prefer while IsRunnin
  • 理解高斯混合模型的概念

    我试图通过阅读在线资源来理解 GMM 我已经使用 K 均值实现了聚类 并且正在了解 GMM 与 K 均值的比较 以下是我的理解 如有错误请指出 GMM 类似于 KNN 在这两种情况下都实现了聚类 但在 GMM 中 每个簇都有自己独立的均值和
  • 非阻塞方法中的饥饿

    一段时间以来 我一直在阅读有关非阻塞方法的内容 这是一段所谓的无锁计数器的代码 public class CasCounter private SimulatedCAS value public int getValue return va
  • 去除字符串的最佳方法是什么?

    我需要具有最佳性能的想法来删除 过滤字符串 I have string Input view 512 3 159 删除 view 和 的最佳性能方法是什么 和引号 我可以做这个 Input Input Replace view Replac
  • C# 写入文件的性能

    我的情况概述 我的任务是从文件中读取字符串 并将它们重新格式化为更有用的格式 重新格式化输入后 我必须将其写入输出文件 这是必须完成的操作的示例 文件行示例 ANO 2010 CPF 17834368168 YEARS 2010 2009
  • 如何找到 IIS 在负载/性能测试期间模拟的平均并发用户数?

    我正在使用 JMeter 进行负载测试 我正在练习通过简单地增加我的分布式 JMeter 测试用例中的线程数并启动测试来查找我们的网络服务器可以处理的最大并发线程 用户 数量 然后 我突然意识到 虽然 MAX 数字可能有用 但REAL我的网
  • 双线性序列给出奇数结果

    我试图让我的表现技能 不存在 达到标准 但在将公式写入代码时遇到了问题 这是我试图将其引用为 转换 为代码的公式 考虑一个序列 u 其中 u 定义如下 号码u 0 1是第一个u 对于每个x in u then y 2 x 1 and z 3
  • 只读有运行时开销吗?

    出于某种原因 我一直认为readonly字段有与其相关的开销 我认为这是 CLR 跟踪是否存在readonly字段是否已初始化 这里的开销是一些额外的内存使用量 用于跟踪状态以及分配值时的检查 也许我这么认为是因为我不知道readonly字
  • 3D 数组到 3D std::vector

    我在代码函数中用 3D std vector 替换了 3D 数组 它进入了无限循环 你能给我一个提示吗 我真的需要使用向量而不是数组 谢谢 我最初的代码是 arr is a 3D array of a sudoku table the 3
  • SQLite .NET 性能,如何加快速度?

    在我的系统上 约 86000 个 SQLite 插入需要长达 20 分钟 意味着每秒约 70 个插入 我要做数百万 我怎样才能加快速度 对每一行的 SQLiteConnection 对象调用 Open 和 Close 会降低性能吗 交易有帮
  • 从开始/结束索引列表创建向量化数组

    我有一个两列矩阵M包含一堆间隔的开始 结束索引 startInd EndInd 1 3 6 10 12 12 15 16 如何生成所有区间索引的向量 v 1 2 3 6 7 8 9 10 12 15 16 我正在使用循环执行上述操作 但我想
  • 在matlab中绘制给定区域内(两个圆之间)的向量场

    我想在 Matlab 中绘制下面的向量场 u cos x x 0 y y 0 v sin x x 0 y y 0 我可以在网格中轻松完成 例如 x 和 y 方向从 2 到 2 x 0 2 y 0 1 x y meshgrid 2 0 2 2
  • 使用 enum.values() 与字符串数组相比,性能是否会受到影响?

    我正在使用枚举来替换String我的 java 应用程序 JRE 1 5 中的常量 当我在不断调用的方法中将枚举视为名称的静态数组时 例如 在渲染 UI 时 是否会对性能造成影响 我的代码看起来有点像这样 public String get
  • 是否可以提高 Mongoexport 速度?

    我有一个 1 3 亿行的 MongoDB 3 6 2 0 集合 它有几个简单的字段和 2 个带有嵌套 JSON 文档的字段 数据以压缩格式 zlib 存储 我需要尽快将其中一个嵌入字段导出为 JSON 格式 然而 mongoexport 需
  • 检测数据集中线性行为的算法

    我已经发布了一个关于对数据集的一部分进行多项式拟合的算法 https stackoverflow com q 17595932 2320757前一段时间收到一些建议去做我想做的事 但我现在面临另一个问题 我尝试应用答案中建议的想法 我的目标

随机推荐