如何用OpenMP实现argmax? [英] How to implement argmax with OpenMP?

查看:135
本文介绍了如何用OpenMP实现argmax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用OpenMP实现argmax.如果很短,我有一个计算浮点值的函数:

I am trying to implement a argmax with OpenMP. If short, I have a function that computes a floating point value:

double toOptimize(int val);

我可以通过以下方法获得使该值最大化的整数:

I can get the integer maximizing the value with:

double best = 0;
#pragma omp parallel for reduction(max: best)
for(int i = 2 ; i < MAX ; ++i)
{
    double v = toOptimize(i);
    if(v > best) best = v;
}

现在,如何获得与最大值对应的值i?

Now, how can I get the value i corresponding to the maximum?

我正在尝试此操作,但想确保它是有效的:

I am trying this, but would like to make sure it is valid:

double best_value = 0;
int best_arg = 0;
#pragma omp parallel
{
  double local_best = 0;
   int ba = 0;
#pragma omp for reduction(max: best_value)
  for(size_t n = 2 ; n <= MAX ; ++n)
  {
    double v = toOptimize(n);
    if(v > best_value)
    {
      best_value = v;
      local_best = v;
      bn = n;
    }
  }
#pragma omp barrier
#pragma omp critical
  {
    if(local_best == best_value)
      best_arg = bn;
  }
}

最后,我应该将best_arg的argmax设置为toOptimize.

And in the end, I should have best_arg the argmax of toOptimize.

推荐答案

您的解决方案完全符合标准.无论如何,如果您愿意添加一些语法糖,则可以尝试以下操作:

Your solution is completely standard conformant. Anyhow, if you are willing to add a bit of syntactic sugar, you may try something like the following:

#include<iostream>

using namespace std;

double toOptimize(int arg) {
  return arg * (arg%100);
}

class MaximumEntryPair {
public:

  MaximumEntryPair(size_t index = 0, double value = 0.0) : index_(index), value_(value){}

  void update(size_t arg) {
    double v = toOptimize(arg);
    if( v > value_ ) {
      value_ = v;
      index_ = arg;
    }
  }

  bool operator<(const MaximumEntryPair& other) const {
    if( value_ < other.value_ ) return true;
    return false;
  }  

  size_t index_;
  double value_;
};



int main() {
  MaximumEntryPair best;
#pragma omp parallel 
  {
    MaximumEntryPair thread_local;
    #pragma omp for
    for(size_t ii = 0 ; ii < 1050 ; ++ii) {
      thread_local.update(ii);
    } // implicit barrier
#pragma omp critical
    {
      if ( best < thread_local ) best = thread_local;
    }

  } // implicit barries
  cout << "The maximum is " << best.value_ << " obtained at index " << best.index_ << std::endl;
  cout << "\t toOptimize(" << best.index_ << ") = " << toOptimize(best.index_) << std::endl;
  return 0;
}

这篇关于如何用OpenMP实现argmax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆