MapReduceExample-2.cpp 1.23 KB
Newer Older
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
1 2 3
#include <iostream>
#include <cstdlib>
#include <TNL/Containers/Vector.h>
4
#include <TNL/Algorithms/Reduction.h>
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
5 6 7 8
#include <TNL/Timer.h>

using namespace TNL;
using namespace TNL::Containers;
9
using namespace TNL::Algorithms;
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
10 11

template< typename Device >
12
double mapReduce( Vector< double, Device >& u )
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
13 14 15 16 17
{
   auto u_view = u.getView();
   auto fetch = [=] __cuda_callable__ ( int i )->double {
      if( i % 2 == 0 ) return u_view[ i ];
      return 0.0; };
18 19
   auto reduce = [] __cuda_callable__ ( const double& a, const double& b ) { return a + b; };
   return Reduction< Device >::reduce( u_view.getSize(), reduce, fetch, 0.0 );
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
20 21 22 23 24 25 26 27
}

int main( int argc, char* argv[] )
{
   Timer timer;
   Vector< double, Devices::Host > host_u( 100000 );
   host_u = 1.0;
   timer.start();
28
   double result = mapReduce( host_u );
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
29 30 31 32 33 34 35
   timer.stop();
   std::cout << "Host tesult is:" << result << ". It took " << timer.getRealTime() << "seconds." << std::endl;
#ifdef HAVE_CUDA
   Vector< double, Devices::Cuda > cuda_u( 100000 );
   cuda_u = 1.0;
   timer.reset();
   timer.start();
36
   result = mapReduce( cuda_u );
Tomáš Oberhuber's avatar
Tomáš Oberhuber committed
37 38 39 40 41 42
   timer.stop();
   std::cout << "CUDA result is:" << result << ". It took " << timer.getRealTime() << "seconds." << std::endl;
#endif
   return EXIT_SUCCESS;
}