Pthread多线程求矩阵乘法并计算运行时间

其中 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;
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值