6
$\begingroup$

Suppose I have a function which I run over a list of values. Is there some way to monitor the progress of this? Perhaps have it take values in a list but as it computes for each element of the list, print the result? Of course, I could run each value individually of course, but since I generate the parameter values as a list it would be more effort to run each parameter value individually.

$\endgroup$
5
$\begingroup$

You can add Print[], PrintTemporary[] or Echo[] to your function definition.

ClearAll[fun] ;
fun[x_] := (Pause[1]; Echo[x] ; x)
list = Range[10] ;
Map[fun,list]

ClearAll[fun] ;
fun[x_] := (Pause[1]; PrintTemporary[x] ; x)
list = Range[10] ;
Map[fun,list]

Also Dynamic[] and Monitor[] can be used:

ClearAll[fun] ;
fun[x_] := (Pause[1]; Dynamic[count] ; count++ ; x)
count = 1 ;
list = Range[10] ;
Monitor[Map[fun,list],ProgressIndicator[count,{1, Length[list]}]]
$\endgroup$
7
$\begingroup$

Here's a solution using ResourceFunction["MonitorProgress"]:

fun[x_] := (Pause@1(*some long computation *);x^2)

ResourceFunction["MonitorProgress"][fun /@ Range@5]
(* {1, 4, 9, 16, 25} *)

$\endgroup$
2
  • $\begingroup$ Nice! Does using this for long lists (e.g. 50000 elements) cause a significant slow-down? $\endgroup$
    – Sterling
    Jan 30 at 23:29
  • $\begingroup$ @Sterling I tried my best to keep the overhead as low as possible, but I would suggest to simply test how big the performance impact is for you, since it will vary from case to case. $\endgroup$
    – Lukas Lang
    Jan 31 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.