How to speed up a process
Total@Range[11111]/Pi // N
(*Out: 1.96501*10^7 *)
In general:
- avoid
For
loops: see: Why should I avoid the For loop in Mathematica? - avoid
Append
/AppendTo
because they generate a new list every time you add an element; instead, generate lists withTable
,Array
,Range
,Reap / Sow
instead; - See also: Alternatives to procedural loops and iterating over lists in Mathematica
Just for some timing context, and to compare For
with Do
:
n = 10^6; rpt = RepeatedTiming;
(For[i = 1; list = {}, i <= n, i++, list = {list, i}]; Total@N@Flatten[list];) // rpt
(For[i = 1; list = {}, i <= n, i++, list = {list, i}]; N@Total@Flatten[list];) // rpt
(list = {}; Do[list = {list, i}, {i, n}]; Total@N@Flatten[list];) // rpt
(list = {}; Do[list = {list, i}, {i, n}]; N@Total@Flatten[list];) // rpt
Total@N@Range[n]; // rpt
N@Total@Range[n]; // rpt
n (n + 1)/2.; // rpt
(* Out:
For loops: 1.35 s
1.40 s
Do loops: 0.980 s
0.887 s
Range: 0.01 s
0.007 s
formula: 1 x 10^-6 s
*)
You can see in @MarcoB's answer the enormous speed up possible.
Even for your code, if you replace the AppendTo
with a different structure, you can get orders of magnitude improvement.
Your code here - note that we don't need l
for anything.
( For[i = 1; list = {}, i <= 11111, i++, AppendTo[list, i/Pi]];
Total@N@list ) //AbsoluteTiming
{2.12476, 1.96501*10^7}
Slight modification results in factor of 100 speed up.
(For[i = 1; list = {}, i <= 11111, i++, list = {list, i/Pi}];
Total@N@Flatten@list) // AbsoluteTiming
{0.0287278, 1.96501*10^7}
n = 11111;
Total@Range[11111]/Pi // N // RepeatedTiming
n (n + 1)/(2. Pi)// RepeatedTiming
{0.000034, 1.96501*10^7}
{1.2*10^-6, 1.96501*10^7}