25
$\begingroup$

I have a function doSomethingComplicated[...] that takes about 10s on average to evaluate. My list, listOfArgs has about 10000 elements. I'd like to monitor the progress of Map[doSomethingComplicated, listOfArgs] without having it ever occupying a big area of the screen. What's best way to do that?

$\endgroup$

2 Answers 2

31
$\begingroup$

Using MapIndexed, which also gives you the index of the element in the list instead of Map would be very convenient. That way, you can set up a Print or a PrintTemporary cell. For example:

Clear[f]
f = (Pause[0.2]; PrintTemporary[First@#2]; #^2) &; (* your complicated function *)
MapIndexed[f, Range[10]]

(* 1
   2
   ...
   ...
  {1, 4, 9, 16, 25, 36, 49, 64, 81, 100} *)

With a PrintTemporary cell, it prints all the output, but the cell disappears when the evaluation is complete, saving you the trouble of cleaning the mess.

You can also print directly to the messages notebook using the PrintToConsole function from my answer here. This keeps your current working notebook clean and you can always check in the other to see the progress.


Another option is to use side-effects and increment a variable, which allows you to use Monitor. For example:

Clear[g]
g = (Pause[0.2]; i = First@#2 + 1; #^2) &;
Block[{i = 1}, Monitor[MapIndexed[g, Range[10]], i]]

See this answer by Brett Champion for the different ways in which you can create a progress bar to suit your needs.

$\endgroup$
2
  • 3
    $\begingroup$ You could write a general function to do this: MapMonitored[f_, args_List] := Module[{x = 0}, Monitor[MapIndexed[(x = #2[[1]]; f[#1]) &, args], ProgressIndicator[x/Length[args]]]] $\endgroup$
    – Ian Hinder
    Commented Apr 10, 2014 at 7:23
  • $\begingroup$ Is there any way to progress-monitor a ParallelMap? MapIndexed is not parallelizable. I don't need exact indexing, just a general sense of progress. $\endgroup$
    – ibeatty
    Commented Mar 22, 2018 at 2:36
12
$\begingroup$

With the 10.3 release and introduction of Echo there is neat simple way:

Just wrap Echo around w/e you map:

Echo[f[#]] & /@ Range[5]

enter image description here

And if you want to suppress large outputs, you can do something like

MapIndexed[(Echo["", First[#2]]; Sin[#1]) &, Range[5]]

enter image description here

which is similar to print but pretty.

$\endgroup$
2
  • 2
    $\begingroup$ This will occupy a very big/tall area of the screen, and in a way Not Pretty^TM doesn't it? $\endgroup$
    – user13253
    Commented Oct 31, 2015 at 23:28
  • 1
    $\begingroup$ @qazwsx i was just updating on a new function. people should use this to their convenience. $\endgroup$ Commented Nov 1, 2015 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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