Untitled
unknown
c_cpp
15 days ago
1.6 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #define MAX 4096 #define MAX_THREADS 8 int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX]; int size, thread_count; void fill_matrix(int size) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { A[i][j] = rand() % 10; B[i][j] = rand() % 10; } } void* multiply_parallel(void* arg) { int tid = *(int*)arg; int from = (tid * size) / thread_count; int to = ((tid + 1) * size) / thread_count; for (int i = from; i < to; i++) for (int j = 0; j < size; j++) { C[i][j] = 0; for (int k = 0; k < size; k++) C[i][j] += A[i][k] * B[k][j]; } pthread_exit(0); } int main() { int sizes[] = {128, 256, 512, 1024, 2048, 4096}; thread_count = MAX_THREADS; for (int s = 0; s < 6; s++) { size = sizes[s]; fill_matrix(size); pthread_t threads[MAX_THREADS]; int thread_ids[MAX_THREADS]; clock_t start = clock(); for (int i = 0; i < thread_count; i++) { thread_ids[i] = i; pthread_create(&threads[i], NULL, multiply_parallel, &thread_ids[i]); } for (int i = 0; i < thread_count; i++) pthread_join(threads[i], NULL); clock_t end = clock(); double time_taken = (double)(end - start) / CLOCKS_PER_SEC; printf("Parallel Time for %dx%d: %.4f seconds\n", size, size, time_taken); } return 0; }
Editor is loading...
Leave a Comment