2 ms·
For caching issues, you could replace the loops by more functional code: write one loop to generate an array of values, and sum them to payoff_sum in a separate
by Someone 11y ago
For caching issues, you could replace the loops by more functional code: write one loop to generate an array of values, and sum them to payoff_sum in a separate loop.
for (int i=0; i<num_sims; i++) {
gauss_bm[i] = gaussian_box_muller();
}
for (int i=0; i<num_sims; i++) {
S_cur[i] = S_adjust * exp(sqrt(v*v*T)*gauss_bm[i]);
}
for (int i=0; i<num_sims; i++) {
payoff[i] += std::max(S_cur[i] - K, 0.0);
}
for (int i=0; i<num_sims; i++) {
payoff_sum += payoff[i];
}
To make this i7-specific, you have to make sure the arrays are mapped to just the right cache lines, so that writing to an array evicts the dat from the array being read from from the cache (hm, maybe that requires combining some of those loops; what does the level 1 cache of these CPUs look like?)
Next step: DRY. Move the for (int i=0; i<num_sims; i++) loop into a function taking a lambda for the loop body. That hides the ugliness of the above code. Here, it probably is fairly easy to accidentally do some extra copying of data.
Next: parallelism. You shouldn't have individual threads process contiguous sections of the arrays; do
for (int i=threadNo; i<num_sims; i+= numThreads) {
instead. And of course, you can multi-thread by having the 4 for loops run in parallel. That, I think, would be the big gain, as it would introduce quite a few data dependencies between threads. It also is in the spirit of the question, I think.
It has nothing to do with the i7, but I would also work on worrying about the value of RAND_MAX. It can be as low as 32767. So, if you want to pick a double from the full range of values in the [-1,1] interval you have to make at least 4 calls to rand(). Making the distribution uniform from there will take quite a bit of work, too (there are as many double values between 1/4 and 1/2 as between 1/2 and 1, but you want to pick the former half as often as the latter)