I'm trying to understand how to save time when calling functions in Mathematica. I wrote this example,
mat1 = RandomInteger[{-100, +100}, {200, 200}];
mat2 = RandomInteger[{-100, +100}, {200, 200}];
Timing[Inverse[mat1]][[1]]
matrixOp1[mat_?MatrixQ] := Module[{lm = mat}, lm + mat2]
Timing[matrixOp1[Inverse[mat1]]][[1]]
matrixOp2[mat_?MatrixQ] := Module[{lm = mat}, lm + lm]
Timing[matrixOp2[Inverse[mat1]]][[1]]
I thought that since module uses local vars, matrixOp2 will work at the same speed as matrixOp1. But this is what I found - the output is as such
Out[134]= 0.0312002
Out[136]= 0.0780005
Out[138]= 0.764405
It looks to me like the Inverse operation occurs many times inside matrixOp2 and I don't understand why. Can anyone please explain?
Thanks
Tamir
TracePrint[]on your functions? – J. M.'s missing motivation Dec 12 '15 at 02:18Inverseoperation happens many times? Result ofInversegoes inmatrixOp2. I believe it has to do with implementation ofModule. There could be a call to create a new context and copy information in there before proceeding and switching to old context after processing. This could be the reason for delay. – Pankaj Sejwal Dec 12 '15 at 04:39+using the new allocated matrixlmin Module context. You can see this by changingModule[{lm = mat}, lm + lm]toModule[{lm = 2*mat}, lm ]which is the same thing, but now its speed is similar to the second case where the+with with the global mat. So the slow down happens to due to adding, element by element,lmtolmin the module content. It should not really be this much slower. This is strange. With compiled languages, the compiler will see this and will do this at compile time! – Nasser Dec 12 '15 at 05:04lm+mat2andlm+lmshould take same time, but it doesn't. In both cases, it is element by element addition. – Pankaj Sejwal Dec 12 '15 at 05:46lm+mat2andlm+lm. In one casemat2is global, while in the second case it is local. There could be difference there in how and/or where each is allocated, or some overhead to access local module level heap. But not knowing internals of Mathematica, this is all speculation. – Nasser Dec 12 '15 at 06:18localis nothing but a new temporary context, but then it can only be a guess. – Pankaj Sejwal Dec 12 '15 at 06:48mat2is integers whilelmis rationals. The comparison betweenlm + mat2andlm + lmis not fair - it's a different arithmetic problem. – Simon Woods Dec 12 '15 at 11:24