How to speed up a process

I am wondering how to speed up the following code: Currently it takes more than two sec to be processed.

Timing[For[i = 1;

list = {}, i <= 11111, i++, l = AppendTo[list, i/Pi]];
Total@N@list]


I am new to Wolfram languages and it's the only thing I could come up with. Any idea ?

Thanks

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}

Total@Range/Pi // N

(*Out: 1.96501*10^7 *)


In general:

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

*)

• Of course, you don't need to know the formula. Mathematica will work it out for you in fraction of the time it took to do the For loop. – mikado Mar 4 at 20:51
n = 11111;
Total@Range/Pi // N // RepeatedTiming
n (n + 1)/(2. Pi)// RepeatedTiming


{0.000034, 1.96501*10^7}

{1.2*10^-6, 1.96501*10^7}

• He. Good old Carl Friedrich to the rescue... :-) I'd go for n (n + 1)/2. / Pi then, to avoid N and squeeze the last few microseconds out – MarcoB Mar 4 at 20:05