Created
June 13, 2014 15:01
-
-
Save 2sin18/43dec7af19c58af4b53e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// It's a CPU-bound program for testing | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <unistd.h> | |
static size_t num_slices; | |
static size_t num_cpus; | |
static pthread_mutex_t pi_lock; | |
static double pi; | |
void* pi_calc(void* pid) { | |
size_t rank = (size_t) pid; | |
double precision = 1.0 / num_slices; | |
double slice = 0; | |
double sum = 0; | |
for (size_t i = rank; i < num_slices; i += num_cpus) { | |
slice = precision * (0.5 + i); | |
sum += 4.0 / (1.0 + slice * slice); | |
} | |
pthread_mutex_lock(&pi_lock); | |
pi += sum * precision; | |
pthread_mutex_unlock(&pi_lock); | |
return NULL; | |
} | |
int main () | |
{ | |
num_slices = 1 << 16; | |
num_cpus = sysconf(_SC_NPROCESSORS_CONF); | |
pi = 0; | |
pthread_mutex_init(&pi_lock, NULL); | |
pthread_t threads[num_cpus]; | |
for (size_t i = 0; i < num_cpus; i++) { | |
cpu_set_t cpuset; | |
CPU_ZERO(&cpuset); | |
CPU_SET(i, &cpuset); | |
pthread_attr_t attr; | |
pthread_attr_init(&attr); | |
// only availbale in Linux, to reduce the number of context switch across many cores | |
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset); | |
// increase the time slice, to reduce the total number of context switch | |
pthread_attr_setschedpolicy(&attr, SCHED_BATCH); | |
pthread_create(&threads[i], &attr, pi_calc, (void *) i); | |
pthread_attr_destroy(&attr); | |
} | |
for (size_t i = 0; i < num_cpus; i++) { | |
pthread_join(threads[i], NULL); | |
} | |
printf("pi = %16.16lf\n", pi); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment