登录论坛

查看完整版本 : 是MATLAB OOP运行缓慢还是我做错了什么?


poster
2019-12-05, 06:26
我正在尝试使用MATLAB (http://en.wikipedia.org/wiki/MATLAB) OOP (http://en.wikipedia.org/wiki/Object-oriented_programming) ,从一开始就模仿了C ++的Logger类,并将所有的字符串帮助器函数都放在String类中,认为能够执行a + b , a == b , a.find( b )代替strcat( ab ) , strcmp( a, b ) ,检索strfind( a, b )第一个元素,等等。

问题:减速

我使用了上面的东西,立即注意到速度急剧下降。我做错了吗(由于我有限的MATLAB经验,这肯定是可能的),还是MATLAB的OOP只会带来很多开销?

我的测试用例

这是我对字符串所做的简单测试,基本上只是添加一个字符串,然后再次删除添加的部分:

注意:实际不要在实际代码中编写像这样的String类! Matlab现在具有本机string数组类型,您应该使用它。

classdef String < handle .... properties stringobj = ''; end function o = plus( o, b ) o.stringobj = [ o.stringobj b ]; end function n = Length( o ) n = length( o.stringobj ); end function o = SetLength( o, n ) o.stringobj = o.stringobj( 1 : n ); end end function atest( a, b ) %plain functions n = length( a ); a = [ ab ]; a = a( 1 : n ); function btest( a, b ) %OOP n = a.Length(); a = a + b; a.SetLength( n ); function RunProfilerLoop( nLoop, fun, varargin ) profile on; for i = 1 : nLoop fun( varargin{ : } ); end profile off; profile report; a = 'test'; aString = String( 'test' ); RunProfilerLoop( 1000, @(x,y)atest(x,y), a, 'appendme' ); RunProfilerLoop( 1000, @(x,y)btest(x,y), aString, 'appendme' ); 结果

1000次迭代的总时间(以秒为单位):

btest 0.550(使用String.SetLength 0.138,String.plus 0.065,String.Length 0.057)

验证0.015


记录器系统的结果也是如此:内部使用String类时frpintf( 1, 'test\n' )对frpintf( 1, 'test\n' )进行1000次调用需要0.1秒,对我的系统进行1000次调用需要7(!)秒(好的,它还有很多其他功能)逻辑,但要与C ++进行比较:在输出端使用std::string( "blah" )和std::cout系统开销与普通std::cout