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
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.