fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <omp.h>
  4.  
  5. #define N 1000 // Matrix size
  6.  
  7. // Function to initialize a matrix
  8. void initialize_matrix(double *matrix, int rows, int cols) {
  9. #pragma omp parallel for
  10. for (int i = 0; i < rows * cols; i++) {
  11. matrix[i] = (double)(rand() % 100) / 100.0; // Random values between 0 and 1
  12. }
  13. }
  14.  
  15. // Function to initialize a vector
  16. void initialize_vector(double *vector, int size) {
  17. #pragma omp parallel for
  18. for (int i = 0; i < size; i++) {
  19. vector[i] = (double)(rand() % 100) / 100.0; // Random values between 0 and 1
  20. }
  21. }
  22.  
  23. // Function to perform matrix-vector multiplication
  24. void matrix_vector_multiply(double *matrix, double *vector, double *result, int rows, int cols) {
  25. #pragma omp parallel for
  26. for (int i = 0; i < rows; i++) {
  27. result[i] = 0.0; // Initialize result element to 0
  28. for (int j = 0; j < cols; j++) {
  29. result[i] += matrix[i * cols + j] * vector[j];
  30. }
  31. }
  32. }
  33.  
  34. int main() {
  35. double *matrix, *vector, *result;
  36. int rows = N, cols = N;
  37.  
  38. matrix = (double *)malloc(rows * cols * sizeof(double));
  39. vector = (double *)malloc(cols * sizeof(double));
  40. result = (double *)malloc(rows * sizeof(double));
  41.  
  42. // Initialize matrix and vector with random values
  43. initialize_matrix(matrix, rows, cols);
  44. initialize_vector(vector, cols);
  45.  
  46. double start_time = omp_get_wtime(); // Start timer
  47.  
  48. // Perform matrix-vector multiplication
  49. matrix_vector_multiply(matrix, vector, result, rows, cols);
  50.  
  51. double end_time = omp_get_wtime(); // Stop timer
  52.  
  53. printf("Time taken: %f seconds\n", end_time - start_time);
  54.  
  55. // Free allocated memory
  56. free(matrix);
  57. free(vector);
  58. free(result);
  59.  
  60. return 0;
  61. }
Success #stdin #stdout #stderr 0.27s 40896KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted