Skip to content

Instantly share code, notes, and snippets.

@5kg
Created January 24, 2013 06:24
Show Gist options
  • Save 5kg/4618112 to your computer and use it in GitHub Desktop.
Save 5kg/4618112 to your computer and use it in GitHub Desktop.
0.900109s
1.508606s
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#define tic() do { struct timespec ts_start, ts_end; clock_gettime(CLOCK_MONOTONIC, &ts_start)
#define toc() clock_gettime(CLOCK_MONOTONIC, &ts_end); \
printf("%lfs\n", (ts_end.tv_sec - ts_start.tv_sec) + (double)(ts_end.tv_nsec - ts_start.tv_nsec)/1e9); } \
while (0)
#define NUM_THREADS 4
#define N 536870912
void* foo(void *);
void* bar(void *);
int* num;
int s[NUM_THREADS];
int main()
{
pthread_t threads[NUM_THREADS];
int ans, ANS = 0;
num = (int*) malloc(sizeof(int) * N);
srand(42);
for (int i = 0; i < N; ++i) {
num[i] = rand() % 100;
ANS += num[i];
}
memset(s, 0, sizeof(s));
ans = 0;
tic();
for (int i = 0; i < NUM_THREADS; ++i)
pthread_create(threads + i, NULL, foo, s + i);
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
ans += s[i];
}
toc();
assert(ans == ANS);
memset(s, 0, sizeof(s));
ans = 0;
tic();
for (int i = 0; i < NUM_THREADS; ++i)
pthread_create(threads + i, NULL, bar, s + i);
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
ans += s[i];
}
toc();
assert(ans == ANS);
return 0;
}
void* foo(void* ptr)
{
int* r = (int*) ptr;
for (int i = (r - s); i < N; i += NUM_THREADS)
*r += num[i];
return NULL;
}
void* bar(void* ptr)
{
int* r = (int*) ptr;
int idx = r - s;
int block = N/NUM_THREADS;
int start = idx * block, end = start + block;
for (int j = 0; j < NUM_THREADS; ++j)
for (int i = start+j; i < end; i+=NUM_THREADS)
*r += num[i];
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment