Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- #include <thread>
- #include <math.h>
- #include <chrono>
- #include <stdlib.h> /* srand, rand */
- #include <time.h> /* time */
- typedef std::chrono::high_resolution_clock Clock;
- using namespace std;
- class Timer
- {
- public:
- Timer() : beg_(clock_::now()) {}
- void reset() { beg_ = clock_::now(); }
- double elapsed() const {
- return std::chrono::duration_cast<std::chrono::microseconds>
- (clock_::now() - beg_).count();
- }
- private:
- typedef std::chrono::high_resolution_clock clock_;
- typedef std::chrono::duration<double, std::ratio<1> > second_;
- std::chrono::time_point<clock_> beg_;
- };
- long Prosti(int n)
- {
- int count=0;
- long a = 2;
- while(count<n)
- {
- long b = 2;
- int prime = 1;// to check if found a prime
- while(b * b <= a)
- {
- if(a % b == 0)
- {
- prime = 0;
- break;
- }
- b++;
- }
- if(prime > 0)
- count++;
- a++;
- }
- return (--a);
- }
- void sporo(int n, int br)
- {
- cout << "thread T" << br << " started" << endl;
- long x = Prosti(n);
- cout << "thread T" << br << " ended with: " << x << endl;
- }
- int main(int argc, char* argv[])
- {
- int threadNumber = 2;
- if( argc >= 2){
- threadNumber = atoi(argv[1]);
- if( threadNumber < 1 || threadNumber >64 ) return 0;
- cout << "Zeljeni broj threadova: " << threadNumber << endl;
- }
- int n = 5000;
- if( argc >= 3){
- n = atoi(argv[2]);
- if( n < 1) return 0;
- cout << "Zeljeni prosti broj: " << n << endl;
- }
- double t1, t2;
- double r1, r2;
- Timer tmr;
- thread p[128];
- // sekvencijalna izvedba X threadova
- t1 = tmr.elapsed();
- cout << endl << "Prvo vrijeme: " << t1 << endl;
- for( int z = 0; z < threadNumber; z++){
- p[z] = std::thread(sporo, std::ref(n), z);
- p[z].join();
- }
- t2 = tmr.elapsed();
- cout << "Drugo vrijeme: " << t2 << endl;
- std::cout << "SEKVENCIJALNO: Proteklo vrijeme (razlika T2-T1): " << t2-t1 << std::endl;
- r1 = t2-t1;
- // paralelna izvedba X threadova
- t1 = tmr.elapsed();
- cout << endl << "Prvo vrijeme: " << t1 << endl;
- for( int z = threadNumber; z < threadNumber*2; z++){
- p[z] = std::thread(sporo, std::ref(n), z);
- }
- for( int z = threadNumber; z < threadNumber*2; z++){
- p[z].join();
- }
- t2 = tmr.elapsed();
- cout << "Drugo vrijeme: " << t2 << endl;
- std::cout << "PARALELNO: Proteklo vrijeme (razlika T2-T1): " << t2-t1 << std::endl;
- r2 = t2-t1;
- // Izvjesce:
- cout << endl << endl << "Paralelno je brze, i to za: " << r1-r2 << endl;
- cout << "Sto iznosi: " << (int) ((r2/r1)*100) << "%" << endl;
- cout << "Broj threadova: " << threadNumber << endl;
- cout << "Racunajuci prosti broj: " << n << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement