在MATLAB中交换两个元素的性能 [英] Performance of swapping two elements in MATLAB

查看:678
本文介绍了在MATLAB中交换两个元素的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

纯粹作为实验,我正在MATLAB中编写排序函数,然后通过MATLAB profiler运行它们.我最困惑的方面是交换元素.

Purely as an experiment, I'm writing sort functions in MATLAB then running these through the MATLAB profiler. The aspect I find most perplexing is to do with swapping elements.

我发现交换矩阵中两个元素的正式"方式

I've found that the "official" way of swapping two elements in a matrix

self.Data([i1, i2]) = self.Data([i2, i1])

运行速度比四行代码慢得多:

runs much slower than doing it in four lines of code:

e1 = self.Data(i1);
e2 = self.Data(i2);
self.Data(i1) = e2;
self.Data(i2) = e1;

第二个示例所花费的总时间比第一个示例中的单行代码短 12倍.

The total length of time taken up by the second example is 12 times less than the single line of code in the first example.

有人会解释为什么吗?

推荐答案

基于发布的建议,我运行了更多测试. 当在分配的LHS和RHS中引用相同的矩阵时,似乎会出现性能下降的情况.

Based on suggestions posted, I've run some more tests. It appears the performance hit comes when the same matrix is referenced in both the LHS and RHS of the assignment.

我的理论是MATLAB使用内部引用计数/写时复制机制,这导致整个矩阵在两面都被引用时在内部被复制. (这是一个猜测,因为我不知道MATLAB的内部原理.)

My theory is that MATLAB uses an internal reference-counting / copy-on-write mechanism, and this is causing the entire matrix to be copied internally when it's referenced on both sides. (This is a guess because I don't know the MATLAB internals).

这是调用函数885548的结果. (这里的差异是我最初发布的四倍,而不是十二倍.每个函数都有额外的函数包装开销,而在我的第一篇文章中,我只是总结了每一行).

Here are the results from calling the function 885548 times. (The difference here is times four, not times twelve as I originally posted. Each of the functions have the additional function-wrapping overhead, while in my initial post I just summed up the individual lines).


 swap1: 12.547 s
 swap2: 14.301 s
 swap3: 51.739 s

代码如下:

 methods (Access = public)
     function swap(self, i1, i2)
        swap1(self, i1, i2);
        swap2(self, i1, i2);
        swap3(self, i1, i2);
        self.SwapCount = self.SwapCount + 1;
    end
 end

 methods (Access = private)
    %
    % swap1: stores values in temporary doubles
    %         This has the best performance
    %
    function swap1(self, i1, i2)
        e1 = self.Data(i1);
        e2 = self.Data(i2);
        self.Data(i1) = e2;
        self.Data(i2) = e1;
    end

    %
    % swap2: stores values in a temporary matrix
    %        Marginally slower than swap1
    %
    function swap2(self, i1, i2)
        m = self.Data([i1, i2]);
        self.Data([i2, i1]) = m;
    end

    %
    % swap3: does not use variables for storage.
    %        This has the worst performance
    %
    function swap3(self, i1, i2)
        self.Data([i1, i2]) = self.Data([i2, i1]);
    end


end

这篇关于在MATLAB中交换两个元素的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆