Advertisement
seba101

[PRIR] PI Watki

Nov 21st, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <conio.h>
  4. #include <stdio.h>
  5. #include <ctime>
  6. #include <Windows.h>
  7.  
  8. using namespace std;
  9.  
  10. double *d;
  11.  
  12. struct lpi {
  13.  
  14.     unsigned int piod, pido;
  15.         double val;
  16. };
  17.  
  18.  
  19. DWORD WINAPI PiFunction(LPVOID lpParam) {
  20.    
  21.     lpi *pidata = (lpi*)lpParam;
  22.     unsigned int i = pidata->piod;
  23.     unsigned int z = pidata->pido;
  24.  
  25.     double pi = 0;
  26.     for (i;i<z;i++) {
  27.  
  28.         int c = 0;
  29.         if (i % 2 == 0) c = 1;
  30.         else c = -1;
  31.  
  32.         pi += double(c) / (2 * i + 1);
  33.  
  34.     }
  35.     pidata->val = pi;
  36.     return 0;
  37. }
  38.  
  39. int main()
  40. {
  41.  
  42.     double pii = 0;
  43.     int threadnumber = 5;
  44.     unsigned int thtemp, thtemp2, tmp = 0;
  45.     unsigned int precision = 10000000;
  46.     double duration;
  47.     d = new double[threadnumber];
  48.     clock_t start;
  49.     start = std::clock();
  50.  
  51.    
  52.  
  53.         for (int i = 0; i < precision; i++) {
  54.             int c = 0;
  55.             if (i % 2 == 0) c = 1;
  56.             else c = -1;
  57.             pii += double(c) / (2 * i + 1);
  58.  
  59.         }
  60.  
  61.     duration = (clock() - start) / (double)CLOCKS_PER_SEC;
  62.  
  63.     cout.precision(10);
  64.     cout << pii * 4 << " W czasie:" << duration << endl;
  65.  
  66.     HANDLE *h = new HANDLE[threadnumber];
  67.     DWORD *TID = new DWORD[threadnumber];
  68.     lpi *PiData = new lpi[threadnumber];
  69.  
  70.     thtemp = precision / threadnumber;
  71.     thtemp2 = thtemp;
  72.     start = std::clock();
  73.         for (int i = 0; i < threadnumber; i++) {
  74.             if (thtemp2 > precision) thtemp2 = precision;
  75.             PiData[i].piod = tmp;
  76.             PiData[i].pido = thtemp2;
  77.             h[i] = CreateThread(NULL, 0, PiFunction, &PiData[i], 0, &TID[i]);
  78.             tmp = thtemp2;
  79.             thtemp2 = thtemp2 + thtemp;
  80.         }
  81.  
  82.     WaitForMultipleObjects(5, h, TRUE, INFINITE);
  83.     duration = (clock() - start) / (double)CLOCKS_PER_SEC;
  84.     double result = 0;
  85.     for (int i = 0; i < threadnumber; i++) {
  86.        
  87.         result += PiData[i].val;
  88.     }
  89.    
  90.     cout << (result)*4.0 << " W czasie:" << duration;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement