Files

89 lines
2.0 KiB
C
Raw Permalink Normal View History

2026-06-09 06:43:13 +02:00
/*
4(psum64.c
2026-05-16 21:52:40 +08:00
1线124816
2026-06-09 06:43:13 +02:00
2psum64.c,task64.c0²+1²++(n-1)²
2026-05-16 21:52:40 +08:00
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/time.h>
#define MAXTHREADS 16
void *sum(void *vargp);
double get_time()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
unsigned long long psum64[MAXTHREADS];
unsigned long long nelems_per_thread;
int main(int argc, char **argv)
{
2026-06-09 06:43:13 +02:00
unsigned long long i, nelems, log_nelems, nthreads, result = 0;
2026-05-16 21:52:40 +08:00
pthread_t tid[MAXTHREADS];
int myid[MAXTHREADS];
2026-06-09 06:43:13 +02:00
if (argc != 3)
2026-05-16 21:52:40 +08:00
{
2026-06-09 06:43:13 +02:00
printf("Usage: %s <nthreads> <log_nelems>\n", argv[0]);
2026-05-16 21:52:40 +08:00
exit(0);
}
nthreads = atoi(argv[1]);
log_nelems = atoi(argv[2]);
nelems = (1LL << log_nelems);
nelems_per_thread = nelems / nthreads;
2026-06-09 06:43:13 +02:00
2026-05-16 21:52:40 +08:00
double t_start = get_time();
2026-06-09 06:43:13 +02:00
for (i = 0; i < nthreads; i++)
2026-05-16 21:52:40 +08:00
{
myid[i] = i;
2026-06-09 06:43:13 +02:00
pthread_create(&tid[i], NULL, sum, &myid[i]);
2026-05-16 21:52:40 +08:00
}
2026-06-09 06:43:13 +02:00
for (i = 0; i < nthreads; i++)
2026-05-16 21:52:40 +08:00
{
2026-06-09 06:43:13 +02:00
pthread_join(tid[i], NULL);
2026-05-16 21:52:40 +08:00
}
2026-06-09 06:43:13 +02:00
for (i = 0; i < nthreads; i++)
2026-05-16 21:52:40 +08:00
{
result += psum64[i];
}
2026-06-09 06:43:13 +02:00
/* 验证公式: 0²+1²+...+(n-1)² = (n-1)*n*(2n-1)/6 */
if (result == (nelems * (nelems - 1) * (2 * nelems - 1)) / 6)
2026-05-16 21:52:40 +08:00
{
2026-06-09 06:43:13 +02:00
printf("Correct result: %llu\n", result);
2026-05-16 21:52:40 +08:00
}
else
{
2026-06-09 06:43:13 +02:00
printf("Wrong result: %llu\n", result);
2026-05-16 21:52:40 +08:00
}
double t_end = get_time();
printf("Time taken: %f seconds\n", t_end - t_start);
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;
2026-06-09 06:43:13 +02:00
unsigned long long i, lsum = 0;
2026-05-16 21:52:40 +08:00
for (i = begin; i < end; i++)
{
lsum += i * i;
}
psum64[myid] = lsum;
return NULL;
2026-06-09 06:43:13 +02:00
}