我在处理这个 black_scholes 代码片段的并行化时遇到了问题,我添加了一个简单的#pragma omp parallel for 但它花费了 50 倍的时间 我确定共享内存有问题,但我真的不知道是什么
black_scholes_iterate (void* the_args)
{
black_scholes_args_t* args = (black_scholes_args_t*) the_args;
/* Unpack the IN/OUT struct */
/* IN (read-only) parameters */
const int S = args->S;
const int E = args->E;
const int M = args->M;
const double r = args->r;
const double sigma = args->sigma;
const double T = args->T;
/* OUT (write-only) parameters */
double* trials = args->trials;
double mean = 0.0;
/* Temporary variables */
gaussrand_state_t gaussrand_state;
void* prng_stream = NULL;
int k;
/* Spawn a random number generator */
prng_stream = spawn_prng_stream (0);
/* Initialize the Gaussian random number module for this thread */
init_gaussrand_state (&gaussrand_state);
/* Do the Black-Scholes iterations */
printf("here2: %d \n",M);
#pragma omp parallel for
for (k = 0; k < M; k++)
{
const double gaussian_random_number = gaussrand1 (&uniform_random_double,
prng_stream,
&gaussrand_state);
trials[k] = black_scholes_value (S, E, r, sigma, T,
gaussian_random_number);
/*
* We scale each term of the sum in order to avoid overflow.
* This ensures that mean is never larger than the max
* element of trials[0 .. M-1].
*/
mean += trials[k] / (double) M;
}
经过进一步测试后,我注意到 for 循环的 htis 部分需要很多时间: const double gaussian_random_number = gaussrand1 (&uniform_random_double,prng_stream, &gaussrand_state);
最佳答案
double *a;
a = malloc(M * sizeof (double));
for (int k = 0; k < M; k++)
{
const double gaussian_random_number = gaussrand1 (&uniform_random_double,
prng_stream,
&gaussrand_state);
a[k]=gaussian_random_number;
}
#pragma omp parallel for
for (int k = 0; k < M; k++)
{
trials[k] = black_scholes_value (S, E, r, sigma, T,
a[k]);
mean += trials[k] / (double) M;
}
@Z Boson 的回答是解决方案,我的速度有了显着提高,这对我帮助很大,非常感谢
关于c - 在 C 中打开 mp 需要更长的时间来处理 black_scholes 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50122474/