Pthread矩阵乘法并输出运行时间
时间: 2023-09-09 07:12:12 浏览: 154
以下是使用Pthreads实现矩阵乘法并输出运行时间的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define MATRIX_SIZE 1000
#define NUM_THREADS 4
int matrix_a[MATRIX_SIZE][MATRIX_SIZE];
int matrix_b[MATRIX_SIZE][MATRIX_SIZE];
int matrix_c[MATRIX_SIZE][MATRIX_SIZE];
void* multiply(void* arg) {
int row = *(int*)arg;
for (int i = 0; i < MATRIX_SIZE; i++) {
for (int j = 0; j < MATRIX_SIZE; j++) {
matrix_c[row][i] += matrix_a[row][j] * matrix_b[j][i];
}
}
return NULL;
}
int main() {
// Initialize matrices
for (int i = 0; i < MATRIX_SIZE; i++) {
for (int j = 0; j < MATRIX_SIZE; j++) {
matrix_a[i][j] = rand() % 10;
matrix_b[i][j] = rand() % 10;
}
}
// Create threads
pthread_t threads[NUM_THREADS];
int rows_per_thread = MATRIX_SIZE / NUM_THREADS;
int rows_remainder = MATRIX_SIZE % NUM_THREADS;
int row_index = 0;
struct timeval start_time, end_time;
gettimeofday(&start_time, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
int rows = rows_per_thread;
if (i == NUM_THREADS - 1) {
rows += rows_remainder;
}
int* arg = malloc(sizeof(int));
*arg = row_index;
pthread_create(&threads[i], NULL, multiply, arg);
row_index += rows;
}
// Wait for threads to finish
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
gettimeofday(&end_time, NULL);
// Print result and running time
long long running_time = (end_time.tv_sec - start_time.tv_sec) * 1000000LL + (end_time.tv_usec - start_time.tv_usec);
printf("Result:\n");
for (int i = 0; i < MATRIX_SIZE; i++) {
for (int j = 0; j < MATRIX_SIZE; j++) {
printf("%d ", matrix_c[i][j]);
}
printf("\n");
}
printf("Running time: %lld microseconds\n", running_time);
return 0;
}
```
在上面的代码中,我们首先初始化了两个矩阵matrix_a和matrix_b,并定义了一个名为multiply的函数来执行矩阵乘法。在主函数中,我们创建了NUM_THREADS个线程,并将每个线程分配一个连续的行范围来执行multiply函数。然后我们等待所有线程完成并打印结果和运行时间。
请注意,我们使用了gettimeofday函数来计算运行时间。该函数返回当前时间(以秒和微秒为单位),我们可以使用它来计算两个时间之间的差异。在本例中,我们将开始时间和结束时间都存储在timeval结构体中,并计算它们之间的微秒差异。
阅读全文