
(*********************************************************************

        Adapted from
        Roman E. Maeder: Programming in Mathematica,
        Second Edition, Addison-Wesley, 1991.

 *********************************************************************)


BeginPackage["Utilities`ShowTime`"]

ShowTime::usage = "On[ShowTime] turns timing info on. Off[ShowTime] turns it off again.
	The time taken for each command is printed before the result (if any)."

ShowTime::twice = "ShowTime is already on."
ShowTime::off = "ShowTime is not in effect."

Begin["`Private`"]

oldPre =.        (* user's value of $Pre *)
ison = False     (* whether ShowTime is currently turned on *)

Attributes[ShowTime] = HoldFirst

ShowTime[expr_] :=
	Module[{timing},
		Block[{$Pre = oldPre},
			timing = Timing[ oldPre[expr] ];
			Print[ timing[[1]] ];
			oldPre = If[ ValueQ[$Pre], $Pre, Identity ];
		];
		If[ !ison, $Pre = oldPre ];  (* turn it off again *)
		timing[[2]]
	]

ShowTime/: On[ShowTime] := (
	If[ ison,
		Message[ShowTime::twice],
	(* else *)
		oldPre = If[ ValueQ[$Pre], $Pre, Identity ];
		$Pre = ShowTime;
		ison = True
	]; )

ShowTime/: Off[ShowTime] := (
	If[ ison,
		ison = False,
	(* else *)
		Message[ShowTime::off]
	]; )

End[]

EndPackage[]

On[ShowTime]
