• Source
    1. #include <omp.h>
    2. #include <stdio.h>
    3. #include <stdlib.h>
    4. #include <time.h>
    5. #include <math.h>
    6.  
    7. #define MAX 100
    8. #define TESTCOUNT 3
    9.  
    10. double start, end;
    11.  
    12. int* InitMas(int size)
    13. {
    14. int *mas = (int*)malloc(sizeof(int) * size);
    15. for (int i = 0; i < size; ++i)
    16. {
    17. mas[i] = rand() % MAX;
    18. }
    19.  
    20. return mas;
    21. }
    22.  
    23. int DotProduct(int *a, int *b, int size)
    24. {
    25. int dotProduct = 0;
    26.  
    27. for (int i = 0; i < size; ++i)
    28. {
    29. dotProduct += a[i] * b[i];
    30. }
    31.  
    32. return dotProduct;
    33. }
    34.  
    35. int ParalDotProduct(int *a, int *b, int size, int chunk)
    36. {
    37. int dotProduct = 0;
    38.  
    39. start = omp_get_wtime();
    40. #pragma omp parallel
    41. {
    42. #pragma omp for schedule(static, chunk) reduction(+:dotProduct)
    43. for (int i = 0; i < size; ++i)
    44. {
    45. dotProduct += a[i] * b[i];
    46. }
    47. }
    48. end = omp_get_wtime();
    49. return dotProduct;
    50. }
    51.  
    52. void Run(int *a, int *b, int size, int threadCount)
    53. {
    54. ParalDotProduct(a, b, size, size / threadCount);
    55.  
    56. printf("Thread count: %d\n", threadCount);
    57. printf("%g s\n", end - start);
    58. }
    59.  
    60. int main()
    61. {
    62. int *a, *b;
    63. int threadCount;
    64. double start, end;
    65.  
    66. srand(time(NULL));
    67. int size = 1000000;
    68. for (int i = 0; i < TESTCOUNT; ++i)
    69. {
    70. printf("Array size: %d\n", size);
    71. a = InitMas(size);
    72. b = InitMas(size);
    73. InitMas(size);
    74.  
    75. start = omp_get_wtime();
    76. DotProduct(a, b, size);
    77. end = omp_get_wtime();
    78. printf("Thread count: %d\n", 1);
    79. printf("%g s\n", end - start);
    80.  
    81.  
    82. Run(a, b, size, 2);
    83. Run(a, b, size, 3);
    84. Run(a, b, size, 4);
    85. Run(a, b, size, 5);
    86. Run(a, b, size, 6);
    87. Run(a, b, size, 7);
    88. Run(a, b, size, 8);
    89. Run(a, b, size, 9);
    90. Run(a, b, size, 10);
    91.  
    92.  
    93. size *= 10;
    94. }
    95. system("PAUSE");
    96. }