#include #include #include #include #define ARRAY_SIZE 15000576 #define NUM_THREADS 8 // Adjust based on your CPU cores typedef struct { float *a; float *b; float *c; int start; int end; } ThreadData; void *add_arrays(void *arg) { ThreadData *data = (ThreadData *)arg; for (int i = data->start; i < data->end; i++) { data->c[i] = data->a[i] + data->b[i]; } return NULL; } double get_time() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec * 1e-6; } int main() { float *a = (float*)malloc(ARRAY_SIZE * sizeof(float)); float *b = (float*)malloc(ARRAY_SIZE * sizeof(float)); float *c = (float*)malloc(ARRAY_SIZE * sizeof(float)); // Initialize arrays for (int i = 0; i < ARRAY_SIZE; i++) { a[i] = i; b[i] = i * 2; } // Create threads pthread_t threads[NUM_THREADS]; ThreadData thread_data[NUM_THREADS]; int chunk_size = ARRAY_SIZE / NUM_THREADS; double start = get_time(); for (int t = 0; t < NUM_THREADS; t++) { thread_data[t].a = a; thread_data[t].b = b; thread_data[t].c = c; thread_data[t].start = t * chunk_size; thread_data[t].end = (t == NUM_THREADS - 1) ? ARRAY_SIZE : (t + 1) * chunk_size; pthread_create(&threads[t], NULL, add_arrays, &thread_data[t]); } // Wait for threads to finish for (int t = 0; t < NUM_THREADS; t++) { pthread_join(threads[t], NULL); } double calc_time = get_time() - start; printf("Pthreads calculation time: %.6f ms\n", calc_time * 1000); // Print a sample of the result for (int i = 0; i < 10; i++) { printf("c[%d] = %f\n", i, c[i]); } free(a); free(b); free(c); return 0; }