Files
C-exp-collection/exp1/psum64.c

79 lines
1.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*任务4(必做编译、测试和运行示例程序psum64.c
1测量线程数为1、2、4、8、16时程序的执行时间计算加速比和效率并做出解释。
2改写该程序psum64.c,保存为task64.c实现计算02+12+… +(n-1)2功能。
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#define MAXTHREADS 16
void *sum(void *vargp);
unsigned long long psum64[MAXTHREADS];
unsigned long long nelems_per_thread;
int main(int argc, char **argv)
{
unsigned long long i,nelems,log_nelems,nthreads,result = 0;
pthread_t tid[MAXTHREADS];
int myid[MAXTHREADS];
if(argc != 3)
{
printf("Usage: %s <nthreads> <log_nelems>\n",argv[0]);
exit(0);
}
nthreads = atoi(argv[1]);
log_nelems = atoi(argv[2]);
nelems = (1LL << log_nelems);
nelems_per_thread = nelems / nthreads;
for ( i = 0; i < nthreads; i++)
{
myid[i] = i;
pthread_create(&tid[i],NULL,sum,&myid[i]);
}
for ( i = 0; i < nthreads; i++)
{
pthread_join(tid[i],NULL);
}
for ( i = 0; i < nthreads; i++)
{
result += psum64[i];
}
if (result == (nelems*(nelems-1))/2)
{
printf("Correct result: %ld\n",result);
}
else
{
printf("Wrong result: %ld\n",result);
}
exit(0);
}
void *sum(void *vargp)
{
int myid = *((int *)vargp);
unsigned long long begin = myid * nelems_per_thread;
unsigned long long end = begin + nelems_per_thread;
unsigned long long i,lsum=0;
for (i = begin; i < end; i++)
{
lsum += i;
}
psum64[myid] = lsum;
return NULL;
}