# How can I optimize this Parallel Map Monitor's code?

I want to know how many tasks each kernel has accomplished with the monitor.

My Attemption:

fun=#^2&;input=Range[10^3];

SetSharedVariable[Finished]
Monitor[Finished={};
ParallelMap[AppendTo[Finished,{fun[#],ToString@\$KernelID}]&,input];
Print@bar;First/@Finished,
bar=Evaluate[Column@Table[
{n,Union[Last/@Finished]}]]/.CountsBy[Finished,Last]
]//Total//AbsoluteTiming

ParallelMap[fun,input]//Total//AbsoluteTiming

Map[fun,input]//Total//AbsoluteTiming


The code is hundred times slower than without monitor.

How can I optimize the monitor?

In other tasks like fun = PrimeQ[2^# - 1] &; input = Range[30000, 30100];, these code works better.

• Don't use AppendTo. It has to copy the whole list in every call. Moreover, writing to any shared variable should be avoided as much as possible because that will force the kernels into waiting for others to finish their write operation. – Henrik Schumacher May 5 '18 at 14:03
• Oh, and this Dynamic bogus will also involve the FrontEnd, and there is hardly any better way than slowing your computations down like communicating with the FrontEnd... ;) – Henrik Schumacher May 5 '18 at 14:08
• Replacing Row@{"Kernel-"<>n<>": ",ProgressIndicator[n/Length[input]]," finished tasks: ",n} by Row@{"Kernel-", n, ": ", ProgressIndicator[n/Length[input]], " finished tasks: ", n} also had some positive effect. – Henrik Schumacher May 5 '18 at 14:15