Slow performance using anonymous functions in MATLAB… have others noticed this?

前端 未结 4 2235
花落未央
花落未央 2020-12-15 13:15

In order to refactor my MATLAB code, I thought I\'d pass around functions as arguments (what MATLAB calls anonymous functions), inspired by functional programming.

H

4条回答
  •  误落风尘
    2020-12-15 13:29

    I faced the same issue as Gary, just thought it would be good to check Andrew's answer on a more recent version of Matlab (2014a) (Mac). The results first:

    direct: 0.0722
    anonymous: 0.3916
    subfunction: 0.2277
    

    And the code I used:

    function []=SpeedTest()
    
    fanon = @(x,y) x*x+y*y;
    
    iter=1000000;
    x=1:iter;
    y=1:iter;
    var1=nan(size(x));
    var2=nan(size(x));
    var3=nan(size(x));
    timefor=struct('direct',nan,'anonymous',nan','subfunction',nan);
    
    tic;
    for i=1:iter
        var1(i)=x(i)*x(i)+y(i)*y(i);
    end
    timefor.direct=toc;
    
    tic;
    for i=1:iter
        var2(i)=fanon(x(i),y(i));
    end
    timefor.anonymous=toc;
    
    tic;
    for i=1:iter
        var3(i)=fsub(x(i),y(i));
    end
    timefor.subfunction=toc;
    
    display(timefor);
    end
    
    function [z]=fsub(x,y)
    z=x*x+y*y;
    end
    

提交回复
热议问题