5
$\begingroup$

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

$\endgroup$

3 Answers 3

5
$\begingroup$

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}

$\endgroup$
8
$\begingroup$
Total@Range[11111]/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 

*)
$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$
    – mikado
    Mar 4, 2019 at 20:51
4
$\begingroup$
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}

$\endgroup$
1
  • 1
    $\begingroup$ 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 $\endgroup$
    – MarcoB
    Mar 4, 2019 at 20:05

Your Answer

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