其中 m ,n, 线程数 从. txt文件中读取,以空格或回车为分隔符
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#define MAX 10000
int thread_count; // number of threads
int m; // row
int n; // column
double A[MAX][MAX]; // matrix input
double x[MAX]; // vector input
double y[MAX]; // result
void* Pth_mat_vect(void* rank);
int main(int argc, char* argv[]) {
struct timeval start;
struct timeval end;
int i, j;
char tmp;
FILE* fpread;
FILE* fpwrite;
long thread;
fpread = fopen(argv[1], "r");
if(fpread == NULL) {
printf("Read error!");
return 0;
}
fscanf(fpread, "%d", &m);
fscanf(fpread, "%d", &n);
fscanf(fpread, "%d", &thread_count);
fclose(fpread);
srand(time(NULL) + rand());
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
A[i][j]= rand() % 5;
}}
for (i = 0; i < n; i++) {
x[i]=rand() % 5;
}
gettimeofday(&start,NULL);
pthread_t* thread_handles;
thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], NULL, Pth_mat_vect, (void*) thread);
}
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], NULL);
}
gettimeofday(&end,NULL);
long long startusec=start.tv_sec*1000000+start.tv_usec;
long long endusec=end.tv_sec*1000000+end.tv_usec;
double elapsed=(double)(endusec-startusec)/1000000.0;
printf("the result of took %.6f seconds\n",elapsed);
free(thread_handles);
printf("%d %d %d", m, n, thread_count);
return 0;
}
void* Pth_mat_vect(void* rank) {
long my_rank = (long) rank;
int i, j;// consider that m cannnot be divided by thread_count exactly
int local_m = m / thread_count;
int my_first_row = my_rank * local_m;// the last thread
int my_last_row = (my_rank + 1) * local_m - 1; //一般选后面的
for (i = my_first_row; i <= my_last_row; i++) {
y[i] = 0.0;
for (j = 0; j < n; j++) {
y[i] += A[i][j] * x[j];
}
}
return NULL;
}