0

The code a=2+2//Timing assigns the variable a to {time,4} . How can I show the evaluation time, but still assign a with the result of 2+2 directly (in one line)?


I have tried defining a custom Timing function (working now)

showTiming[in_] :=  Block[{res}, res = Timing[in]; Print[res[[1]], " s"]; res[[2]] ]
SetAttributes[showTiming, HoldAll] (* <- IMPORTANT!*)

a=2+2//showTiming

Albercoc
  • 988
  • 3
  • 13
  • Obviously 2+2 is going to show zero... 2+2 is extremely fast to calculate. If you want to test it more, try timing something difficult like factoring big numbers e.g a = FactorInteger[Times @@ RandomPrime[2^70, 2]] – flinty May 21 '21 at 12:41

3 Answers3

5

The only thing missing from your definition of showTiming was a HoldAll or HoldFirst attribute. Without that attribute the argument in is evaluated before being handed off to showTiming.


Since V12.2 there is a function, EchoTiming, that effectively does the same thing as your function, but using Echo instead of Print to display the time.

enter image description here

Brett Champion
  • 20,779
  • 2
  • 64
  • 121
1

In one line this looks a bit ugly:

(a = Last@#; Print@*First@#) &@Timing[2 + 2]
(* 0. and a is set to 4 *)

With a harder workload:

(a = Last@#; Print@*First@#) &@Timing[
  FactorInteger[Times @@ RandomPrime[2^70, 2]]
]
(* 0.34375, and a is set to the factorization *)

Maybe you could have this as a function like:

TimedExpr[expr_] := (Last@#; Print@*First@#;) &@Timing[expr]
SetAttributes[TimedExpr, HoldAll]

(* example *) TimedExpr[ b = FactorInteger[Times @@ RandomPrime[2^70, 2]] ]

flinty
  • 25,147
  • 2
  • 20
  • 86
  • (for other users): this does not show the result of the evaluation. But removing the semicolon in the parenthesis achieves that, (Print@*First@#; Last@#) &. – Albercoc May 21 '21 at 14:31
  • Thank you @flinty for taking the time to do this function. I would have liked to accept both answers. – Albercoc May 21 '21 at 14:33
1
a = 2+2; // Timing // First

You can leave out the // First for simplicity.

Roman
  • 47,322
  • 2
  • 55
  • 121