I have written a C++-program for calculating pi via the "throw random points into a quarter of a circle and count them etc.". Now my program is a bit slow in my opinion, and I have thought about some improvements to speed it up (source code is below).
My first idea is to make it multithreaded using OpenMP, i.e. split the code between (I) and (II) up into several threads so that I have for example nearly ten times more rounds without having to wait longer (on a octacore system).
Another idea I had was to use global variables and to use pointer, so that I just have to copy pointer and not tuples of integer. Drawback is (idk)?
So, what else can I do to speed the program up? I am working mainly with windows, but I can use Unix/Linux too.
Thank you very much!
Code Section:
#include <cstdlib>
#include <iostream>
#include <tuple>
#include <math.h>
#include <time.h>
#include <omp.h>
#include <sys/time.h>
#define RAND_MAX 32000
#define LOOPS 1000000
inline std::tuple<int, int> Throw_points(void)
{
int i = 0, j = 0;
i = rand() % 1000;
j = rand() % 1000;
return std::make_tuple(i, j);
}
inline bool is_in_circle(std::tuple<int, int> point)
{
if ((pow(std::get<0>(point), 2) + pow(std::get<1>(point), 2)) <= pow(1000, 2))
return true;
else
return false;
}
inline double pi(void)
{
srand(time(NULL));
long long int in_circle = 0;
long long int out_circle = 0;
for (int i = 0; i < LOOPS; i++)
{
if (is_in_circle(Throw_points()))
in_circle++;
out_circle++;
}
return double(in_circle) / double(out_circle) * 4;
}
Call via pi()