Strumenti Utente

Strumenti Sito


magistraleinformaticanetworking:spm:spm1213_c_ff_load_balancing_chunk
chunk.cpp
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
 
#include <omp.h>
#include "ff/farm.hpp"
 
using namespace std;
using namespace ff; 
 
float **a; 
int     n; 
 
float calc(float x) {
  long iter = (long) x; 
  for(long i=0; i<iter; i++) 
    x = sin(x); 
  return(x);
}
 
typedef struct __chunk {
  int from; 
  int to; 
  float sum; 
} CHUNK; 
 
class Worker : public ff_node {
  void * svc(void * t) {
 
    CHUNK * task = (CHUNK *) t;
 
    for(int i=task->from; i<task->to; i++) {
      for(int j=0; j<n; j++) {
	a[i][j] = calc(a[i][j]);
	task->sum += a[i][j]; 
      }
    }
    return (t); 
  }
};
 
class Emitter : public ff_node {
private:
  int chunk; 
public: 
  Emitter(int c): chunk(c) {}
 
  void * svc(void * t) {
    a = new float * [n];
    for(int i=0; i<n; i++) 
      a[i] = new float[n];
 
    for(int i=0; i<n; i++) 
      for(int j=0; j<n; j++) 
	a[i][j] = i* 100 + j * 10; 
 
    int sent = 0; 
    while(sent < n) {
      CHUNK * c = new CHUNK; 
      c->from = sent; 
      c->to   = (sent + chunk < n ? sent + chunk : n); 
      sent    = c->to;
 
      ff_send_out((void *) c);
    }
 
    return(EOS); 
  }
};
 
 
class Collector : public ff_node {
private: 
  float sum; 
public: 
 
  int svc_init() {
    sum = 0.0; 
    return(0); 
  }
 
  void svc_end() {
    cout << "sum is " << sum << endl; 
    return; 
  }
 
  void * svc(void * t) {
    CHUNK * x = ((CHUNK *) t) ;
    sum += x->sum; 
    return GO_ON; 
  }
};
 
int main(int argc, char * argv[]) {
 
  if(argc == 1) {
    cout << "Usage is:\n" << argv[0] << " veclen chunk [T(1)] numthread " << end
l; 
    return(0);
  }
 
  n   = atoi(argv[1]); 
  int chunk = atoi(argv[2]); 
  int nw; 
  float tc1; 
 
  if(argc == 4) {
    nw  = atoi(argv[3]); 
  } 
  if(argc == 5) {
    nw = atoi(argv[4]); 
    tc1 = atof(argv[3]); 
  }
 
 
  float sum = 0.0;
  ff_farm<> farm; 
 
  vector<ff_node *> workers;
  for(int i=0;i<nw;++i) 
    workers.push_back(new Worker);
  farm.add_workers(workers); 
  farm.add_collector(new Collector); 
  farm.add_emitter(new Emitter(chunk)); 
 
  float ts0 = omp_get_wtime();
  farm.run_and_wait_end();
  float ts1 = omp_get_wtime();
  float tc = ts1 - ts0; 
 
  cout << tc << " " ;
  if(argc==5) {
    cout << " sp = " << tc1 / tc;
  } 
  cout << endl; 
  return(0); 
 
}
magistraleinformaticanetworking/spm/spm1213_c_ff_load_balancing_chunk.txt · Ultima modifica: 24/04/2013 alle 06:24 (6 anni fa) da Marco Danelutto