0

In Leonid Shifrin's book (page 357 or http://www.mathprogramming-intro.org/book/node558.html) i am getting opposite performance speeds for two implementations that check whether a matrix is indeed a diagonal matrix

The book mentions the two constructs:

diagonalQ2[m_?MatrixQ]/;Equal@@Dimensions[m]:=
(Total@*Abs@*Flatten@*Rest@*Transpose)[MapIndexed[RotateLeft[#1,First[#2]-1]&,m]] === 0;

second construct:

diagonalQNew1[m_?MatrixQ] /; Equal @@ Dimensions[m] := Module[{len = Length[m]},
Flatten[MapThread[Delete, {m, Range[len]}]] === Array[0 &, {len*(len - 1)}]
];

the book claims that diagonalQNew1 is faster than diagonalQ2. Leonid mentions two tests:

testiden = IdentityMatrix[400];
testmatr = Array[Random[]&, {400,400}];

his results:

diagonalQ2[testiden]//Timing (* 0.07, True *)
diagonalQ2[testmatr]//Timing (* 0.261, False *)

compared to

diagonalQNew1[testiden]//Timing (* 0.02, True *)
diagonalQNew1[testmatr]//Timing (* 0.17, False *)

my results (version 11.1)

However, in my test with version 11.1 I have observed diagonalQ2 to be approximately 4X faster.

diagonalQ2[testiden] // RepeatedTiming (* {0.0038, True} *)
diagonalQ2[testmatr] // RepeatedTiming (* {0.004, False} *)

versus

diagonalQNew1[testmatr] // RepeatedTiming (* {0.019, False} *)
diagonalQNew1[testiden] // RepeatedTiming (* {0.013, True} *)

I am confused as to what can be the cause of this significant perfomance increase?

Ali Hashmi
  • 8,950
  • 4
  • 22
  • 42
  • I'm not sure there is a significant performance increase. The usage of @* suggests that the book was written with at least Mathematica 10.0, but I get roughly the same performance in both version 10.0 and 11. – C. E. Jul 12 '17 at 22:21
  • @C.E. let me put it this way: why is diagonalQNew1 performing faster than diagonalQ2 – Ali Hashmi Jul 12 '17 at 22:31
  • @C.E. sorry but I have used @* in the code. The code in the book goes without it. – Ali Hashmi Jul 12 '17 at 22:33
  • 1
    ok, then maybe the tests are accurate for an even older version, like 9. What I'd do to figure out why one is faster than the other is to use Runtime`Profile as in this answer. If I had access to Mathematica 9.0, then I could also have figured out what the reason for the performance increase is by profiling the code in that version as well. – C. E. Jul 12 '17 at 22:47

0 Answers0