Skip to content

Instantly share code, notes, and snippets.

@lerno
Last active December 11, 2022 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lerno/766638b87a0532532c7d0173ff408a77 to your computer and use it in GitHub Desktop.
Save lerno/766638b87a0532532c7d0173ff408a77 to your computer and use it in GitHub Desktop.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <pthread.h>
#include <stdbool.h>
static bool is_prime(int n) {
int i = 5;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
while (i * i <= n)
{
if (n % i == 0) return false;
i += 2;
if (n % i == 0) return false;
i += 4;
}
return true;
}
void *thread_find_prime(void *data)
{
int *repeats = data;
for (int i = 0; i < *repeats; i++)
{
uint64_t startt = clock();
const int start = 1;
const int stop = 1000000;
int sum = 0;
int count = 0;
int sc = 0;
int p;
for (p = start; p < stop; p++)
{
if (is_prime(p))
{
count++;
sum += p;
if (is_prime(sum))
{
sc++;
}
}
}
printf("%.2fms There are %d summerized primes in [%d, %d)\n", ((clock() - startt) / (double)CLOCKS_PER_SEC) * 1000, sc, start, stop);
}
return NULL;
}
int main(int a, char **args)
{
uint64_t startt = clock();
int threadcount = atoi(args[1]);
pthread_t *threads = malloc(sizeof(pthread_t) * (unsigned)threadcount);
int repeats = 10 / threadcount;
for (int i = 0; i < threadcount; i++)
{
pthread_t *thread = threads + i;
if (pthread_create(thread, NULL, thread_find_prime, &repeats)) exit(1);
}
for (int i = 0; i < threadcount; i++)
{
pthread_join(threads[i], NULL);
}
printf("%.2fms Total time\n", ((clock() - startt) / (double)CLOCKS_PER_SEC) * 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment