I am testing the speed of Mathematica's latest version against a VB macro for simple loops to evaluate Pi.
So the VB macro is:
c = 0: n = 1000000: m = n * n
For i = 0 To n
For j = 0 To n
If (i * i + j * j) / m < 1 Then
c = c + 1
End If
Next
Next
Selection.Text = 4 * c / m
I know how to write the corresponding code in Mathematica, but I do not know the intricacies of Mathematica regarding faster program execution. Can you help please by giving me an example of best optimized code for this example?
There are approximately 4 trillion operations in this example and the VB macro takes less than a day to execute...
This program partitions a quarter of a circular area of radius = 1 to smaller squares of area $1/n^2$ then counts them and adds them together. Essentially, a Monte Carlo Method but with randomness removed.
With your help I have created this faster code which uses parallel computing:
arg = Range[ 0, 1000000]; calcCompiled =
Compile[{i},
Module[{c = 0}, Do[If[(i*i + j*j)/1000000^2 < 1, ++c], {j, 1000000}];
c], CompilationTarget -> "C", RuntimeAttributes -> {Listable},
Parallelization -> True,
RuntimeOptions -> "Speed"];
AbsoluteTiming@N[4 Total[calcCompiled[arg]]/1000000^2, 20]
Any suggestions how to make this faster are welcome....
Raw InputFormand format as a code block. – Bob Hanlon Dec 26 '18 at 16:13c=1and that takes an unmeasurable small amount of time to execute. That is eactly one integer operation. But I am not fluent in Visual Basic, so I could be wrong. In total, I do not understand your request. – Henrik Schumacher Dec 26 '18 at 16:32Compile). Try a functional algorithm instead. But if VB compiles to low-level C anyway, this might still not quite be the right comparison. Speed tests are tricky if you need to get a truly meaningful result. – b3m2a1 Dec 26 '18 at 19:20