- 001
- 002
- 003
- 004
- 005
- 006
- 007
- 008
- 009
- 010
- 011
- 012
- 013
- 014
- 015
- 016
- 017
- 018
- 019
- 020
- 021
- 022
- 023
- 024
- 025
- 026
- 027
- 028
- 029
- 030
- 031
- 032
- 033
- 034
- 035
- 036
- 037
- 038
- 039
- 040
- 041
- 042
- 043
- 044
- 045
- 046
- 047
- 048
- 049
- 050
- 051
- 052
- 053
- 054
- 055
- 056
- 057
- 058
- 059
- 060
- 061
- 062
- 063
- 064
- 065
- 066
- 067
- 068
- 069
- 070
- 071
- 072
- 073
- 074
- 075
- 076
- 077
- 078
- 079
- 080
- 081
- 082
- 083
- 084
- 085
- 086
- 087
- 088
- 089
- 090
- 091
- 092
- 093
- 094
- 095
- 096
- 097
- 098
- 099
- 100
#include <stdio.h>
#include <malloc.h>
#include <sys/time.h>
#include <pthread.h>
#define MAXPRIME 10000001
char sieve[MAXPRIME];
typedef struct {
int id, min, max, step;
unsigned long long result;
} Task;
void primes() {
printf("Searching prime numbers ...\n");
sieve[0] = sieve[1] = 1;
for (int i=2; i<MAXPRIME; i++)
sieve[i] = 0;
int i = 2;
while (1) {
while (i<MAXPRIME && sieve[i])
i++;
if (i >= MAXPRIME)
break;
for (int j=i*2; j<MAXPRIME; j+=i)
sieve[j] = 1;
i++;
}
}
double utime() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
unsigned long long calc(int thread, int min, int max, int step) {
unsigned long long sum = 0;
double start = utime();
int nextshow = max+1;
for (int n=max; n>=min; n-=step) {
if (!sieve[n]) {
sum += 1;
continue;
}
if (n <= nextshow && n > min) {
double elapsed = utime() - start, eta = elapsed/(max-n)*(n-min);
printf("Thread %d: current=%d elapsed=%lfs eta=%lfh\n", thread, n, elapsed, eta/3600);
nextshow = n < 10000 ? 0 : n - 10000;
}
int b;
asm("movl %1, %%ecx\n"
"1: dec %%ecx\n"
"movl %%ecx, %%eax\n"
"imull %%eax\n"
"idivl %1\n"
"cmpl %%ecx, %%edx\n"
"jnz 1b\n"
"movl %%ecx, %0"
: "=g"(b)
: "r"(n)
: "%eax", "%ecx", "%edx");
sum += b;
}
return sum;
}
void * thread(void *arg) {
Task *task = arg;
printf("Thread %d: working from %d to %d step %d\n", task->id, task->min, task->max, task->step);
task->result = calc(task->id, task->min, task->max, task->step);
printf("Thread %d: partial result is %llu\n", task->id, task->result);
return NULL;
}
int main() {
primes();
int threads = 4;
int max = 10000000;
pthread_t tid[10];
Task tasks[10];
for (int i=0; i<threads; i++) {
tasks[i].id = i;
tasks[i].min = 1;
tasks[i].max = max-i;
tasks[i].step = threads;
pthread_create(&tid[i], NULL, thread, &tasks[i]);
}
unsigned long long sum = 0;
for (int i=0; i<threads; i++) {
pthread_join(tid[i], NULL);
sum += tasks[i].result;
}
printf("Result: %llu\n", sum);
return 0;
}