c - 在 C 中打开 mp 需要更长的时间来处理 black_scholes 算法

标签 c openmp pragma

我在处理这个 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/

相关文章:

c++ - 嵌套并行 omp v. 2.0 性能

haskell - Forall'd 约束在 RULE 中不受 lhs 约束

c++ - GCC 插件,添加新的优化编译指示

c - 我如何配置 Vim 以在 Windows 上使用 Borland 的编译器编译 C 代码?

c - 在这种情况下,最轻(最)重的 GCC 内存屏障是什么?

c - 在 OpenMP 中启动多少个线程?

外部 dll 中的 c#/wpf OpenMP

c - 除了最后一个之外,所有 #pragma GCC 诊断均被忽略

c - Digital Mars DOS _fmalloc 没有提供指向可用内存的指针?

c - 通过引用传递指针数组