Strumenti Utente

Strumenti Sito


magistraleinformaticanetworking:spm:spm1617cilk

Sample Cilk plus code

Fibonacci

Codice:

"fib.cpp"
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
 
#include <stdlib.h>
 
int fib(int n) {
  // std::cout << "This is thread " << std::this_thread::get_id()
  // 	    << std::endl; 
  if(n<2)
    return(1);
  else {
#ifdef WITHCILK
    int f1 = _Cilk_spawn fib(n-1);
    int f2 = _Cilk_spawn fib(n-2);
    _Cilk_sync;
    return (f1 + f2); 
#else
    return(fib(n-1)
	   +
	   fib(n-2));
#endif
  }
}
 
int main(int argc, char * argv []) {
 
  int n = atoi(argv[1]);
  std::vector<int> v;
 
  std::chrono::time_point<std::chrono::system_clock> start, stop;
  start = std::chrono::system_clock::now();
  for(int i=0; i<=n; i++)
    v.push_back(fib(i));
  stop = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed_seconds = stop-start;
 
  for(int i=0; i<=n; i++) 
    std::cout <<  "fib(" << i << ")=" <<
      fib(i) << " ";
  std::cout << std::endl;
  std::cout << "Computed in " << elapsed_seconds.count()
	    << " secs " << std::endl; 
  return(0); 
}

Makefile

"Makefile"
SOURCE  = fib
CFLAGS  = -std=c++11 -g
LDFLAGS = -lm
CXX     = g++-5
 
all:	seq par
 
seq: 	$(SOURCE).cpp
	$(CXX) $(CFLAGS) -o $(SOURCE)seq $(SOURCE).cpp
 
par: 	$(SOURCE).cpp
	$(CXX) $(CFLAGS) -fcilkplus -o $(SOURCE)par -DWITHCILK $(SOURCE).cpp
 
clean:
	rm -f $(SOURCE)par $(SOURCE)seq

Dummy

"dum.cpp"
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <math.h>
 
#include <stdlib.h>
 
float loose(float x, long n) {
  for(int i=0; i<n; i++)
    x = sin(x);
  return(x);
}
 
int main(int argc, char * argv []) {
 
  int k,n = atoi(argv[1]);
  std::vector<float> v;
 
  std::chrono::time_point<std::chrono::system_clock> start, stop;
  start = std::chrono::system_clock::now();
#ifdef WITHCILK
  _Cilk_for (int k=0;k<=n;k++)
#else
    for(int k=0;k<=n;k++)
#endif
    v.push_back(loose(1.0,1000000));
 
  stop = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed_seconds = stop-start;
  std::cout << "Computed in " << elapsed_seconds.count()
	    << " secs " << std::endl; 
 
  for(int i=0; i<=n; i++) 
    std::cout << // "fib(" << i << ")=" <<
      v[i] << " ";
  std::cout << std::endl;
  return(0); 
}
magistraleinformaticanetworking/spm/spm1617cilk.txt · Ultima modifica: 08/11/2016 alle 16:45 (8 anni fa) da Marco Danelutto