Advertisement
cardel

Ejercicio G50

Aug 21st, 2024
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <chrono>
  4.  
  5. const int SIZE_VECTOR = 1000000;
  6.  
  7. std::vector<long> vector(SIZE_VECTOR);
  8.  
  9. /*
  10. Incializar el vector con valores desde 1 hasta SIZE_VECTOR
  11. */
  12. void initialize(int start, int end) {
  13.     for (int i = start; i < end; ++i) {
  14.         vector[i] = i;
  15.     }
  16.  
  17. }
  18.  
  19. /*
  20.   Elevar al cuadrado cada elemento del vector
  21. */
  22. void square(int start, int end) {
  23.     for (int i = start; i < end; ++i) {
  24.         vector[i] = vector[i] * vector[i];
  25.     }
  26. }
  27.  
  28. /*
  29.   Sumar todos los elementos del vector
  30. */
  31. long sum(int start, int end) {
  32.     long sum = 0;
  33.     for (int i = start; i < end; ++i) {
  34.         sum += vector[i];
  35.     }
  36.     return sum;
  37. }
  38.  
  39. int main() {
  40.     auto start_time = std::chrono::high_resolution_clock::now();
  41.  
  42.     initialize(0, SIZE_VECTOR/2);
  43.     initialize(SIZE_VECTOR/2, SIZE_VECTOR);
  44.  
  45.     square(0, SIZE_VECTOR/2);
  46.     square(SIZE_VECTOR/2, SIZE_VECTOR);
  47.  
  48.     long resultA = sum(0, SIZE_VECTOR/2);
  49.     long resultB = sum(SIZE_VECTOR/2, SIZE_VECTOR);
  50.  
  51.     long result = resultA + resultB;
  52.     std::cout << "Result: " << result << std::endl;
  53.  
  54.     auto end_time = std::chrono::high_resolution_clock::now();
  55.     std::chrono::duration<double> duration = end_time - start_time;
  56.  
  57.     std::cout << "\nTime sequential: " << duration.count() << " seconds" << std::endl;
  58.  
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement