What generates the In/Out CellLabels in Mathematica and how can I add automatic Timing to them?

后端 未结 3 974
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-16 00:07

When Mathematica evaluates a cell, it gives the Input cell and Output cell the CellLabels In[$Line]:= and Out[$Line]= where $Line is a counter that get

3条回答
  •  渐次进展
    2021-02-16 00:52

    OK, the discussion on Physics Forums has lead to this quite hackish solution (now cleaned up a little):

    SetAttributes[Timeit, HoldAll]
    Timeit[x_] := With[{t = Timing[x]}, Module[{out, form},
      If[TrueQ[MemberQ[$OutputForms, Head[t[[2]]]]],
        out = First[t[[2]]]; form = "//" <> ToString[Head[t[[2]]]], 
        out = t[[2]]; form = ""];
      If[out === Null, Null,
        CellPrint[ExpressionCell[t[[2]], "Output", CellLabelAutoDelete -> False,
          CellLabel -> StringJoin["(", ToString[t[[1]]], ")",
            "Out[", ToString[$Line], "]", form, "="]]];
      Unprotect[Out]; Out[$Line] = out; Protect[Out]; out;]];]
    $Pre = Timeit;
    

    To make the CellLabels persistent so that you don't lose the timing when you Save and Load the notebook, you can modify the stylesheet so that the Output cells have the option CellLabelAutoDelete -> True. (Edit: Now added to the CellPrint command.)

    Any better solutions are more than welcome.

提交回复
热议问题