Visto che non so come usare un profiler (appena ho tempo imparerò) ho spezzettato i punti del codice per vedere dove matlab va meglio di c++.
ho separato i calcoli dalla generazione dei numberi casuali e questi sono i risulstati:
matlab
codice:
Elapsed time is 0.066459 seconds.
Elapsed time is 0.161765 seconds.
c++
codice:
Elapsed time: 0.170000
Elapsed time: 0.149000
Quindi in c++ sono gia molto piu veloce nella parte di calcoli (considera che matlab lavora gia in multithreading e il mio pc ha due core, mentre il mio codice c++ deve essere ancora modificato per far andare piu calcoli in parallelo
direi che il problema è il generatore di numeri casuali!!
eccoti il codice con cui ho registrato i tempi:
codice:
inline double Margrabe_option_MC_price(double r, double t, double s1, double s2, double q1, double q2,
double std1, double std2, double corr, long iterations){
clock_t start, stop;
start = clock();
//variables and objects initialization
register long x,y;
double price = 0; //the final price will be stored here
double payoff;
double *z1; //to store generated random numbers
double matr21, matr22;
double sigma1, sigma2;
double part1, part2, sqrtt;
//memory allocation
z1 = new double[iterations*2];
//seeding the random number generator
#ifdef RANDOM_MODE_TR1
Myeng eng;
ndistr stdnorm(0, 1); //creating the standard normal distribution generator
eng.seed((unsigned long) time(NULL));
#endif
#ifdef RANDOM_MODE_Mersenne_twister
init_genrand((int)time(NULL));
#endif
//calculating sigmas
matr21 = corr * std2;
matr22 = sqrt(1-corr*corr) * std2;
//precalculating fixed part of drive formula
part1 = exp((r - q1 - 0.5*std1*std1)*t);
part2 = exp((r - q2 - 0.5*std2*std2)*t);
sqrtt = sqrt(t);
stop = clock();
printf("Elapsed time: %f\n", (double)(stop-start)/CLOCKS_PER_SEC);
start = clock();
for(x=0; x < iterations ;x++){
y=x+x;
//generating random numbers
#ifdef RANDOM_MODE_TR1
z1[y] = stdnorm(eng);
z1[y+1] = stdnorm(eng);
#endif
#ifdef RANDOM_MODE_Mersenne_twister
z1[y] = normsinv(genrand_real3());
z1[y+1] = normsinv(genrand_real3());
#endif
}
stop = clock();
printf("Elapsed time: %f\n", (double)(stop-start)/CLOCKS_PER_SEC);
start = clock();
for(x=0; x < iterations ;x++){
y=x+x;
//creating sigmas
sigma1 = z1[y] * std1;
sigma2 = matr21 * z1[y] + matr22 * z1[y+1];
//calculating payoff
payoff = (s1 * part1 * exp(sqrtt * sigma1)) - (s2 * part2 * exp(sqrtt * sigma2));
if(payoff > 0) price += payoff;
}
price /= iterations;
price *= exp((-r)*t);
delete [] z1;
stop = clock();
printf("Elapsed time: %f\n", (double)(stop-start)/CLOCKS_PER_SEC);
return price;
}