I want to get into programming Monte Carlo simulations, so I decided to evaluate the performance of programming languages. Here I wrote a simple Monte Carlo simulation for the value of PI in Fortran and C++. The two codes are basically identical. However, the Fortran code appears to be performing noticeably better. I am hoping others can confirm this.
Here's the Fortran below: I compiled using G95 (Windows) with no options.
program monte_pi
implicit none
integer niter,i,j
integer seed
real*4 count
real *8 x,y,pi(200),z
real*8 rand
niter = 2293544
seed = 35791246
call srand (seed)
do j= 1,200
niter = niter+100
count =0
do i=1,niter
x=rand()
y=rand()
z= x*x +y*y
if (z .le. 1) count =count+1
end do
pi(j)= count/niter*4.
write(*,*) niter,pi(j)
end do
end
And here is the C++ code: I compiled using g++ (Mingw) C++11 with -O3.
#include <random>
#include <stdlib.h>
template<int N>
class MonteCarloPi
{
private:
int niter=2293544, seed = 35791246;
double pi[N];
double x,y,z,count;
public:
template<int I=N>
void runsimulation()
{
std::default_random_engine e1(seed);
std::uniform_real_distribution<double> genrand(0, 1);
for(int j=0; j< I; j++) {
niter = niter+100;
count = 0.0;
for(int i=0; i< niter; i++)
{
x = genrand(e1);
y = genrand(e1);
z = (x*x) + (y*y);
if ( z <= 1 ) count = count + 1.0;
}
pi[j] = count/(double)niter*4.0;
printf("%d %f\n",niter,pi[j]);
}
}
};
int main()
{
MonteCarloPi<200> mcp;
mcp.runsimulation();
return 0;
}
Can anyone else confirm that the Fortran way is indeed faster?
I did not add any time functions to the code because I'm doing this on an older x86 PC where the only way of getting millisecond timing is to use the Win32 API functions. Since that isn't portable I omitted that, but feel free to add a timing function.
Aucun commentaire:
Enregistrer un commentaire