/perf/kseta

To get this branch, use:
bzr branch http://darksoft.org/webbzr/perf/kseta

« back to all changes in this revision

Viewing changes to tutorials/4_pi/pi.c

  • Committer: Suren A. Chilingaryan
  • Date: 2013-10-08 23:53:50 UTC
  • Revision ID: csa@dside.dyndns.org-20131008235350-hsu8oukzkh05gtcm
Add tutorials

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include <stdio.h>
 
2
#include <stdlib.h>
 
3
#include <string.h>
 
4
#include <locale.h>
 
5
 
 
6
#define ITERATIONS 10
 
7
#define DEFAULT_SIZE 100
 
8
 
 
9
size_t exercise(unsigned long *res, size_t size, int iterations);
 
10
int exercise_init(const char *name, size_t size);
 
11
void exercise_free();
 
12
 
 
13
extern int exercise_required_alignment;
 
14
 
 
15
size_t get_padded_size(size_t size, size_t block_size) {
 
16
    size_t blocks = (size / block_size);
 
17
    size_t inc = blocks * block_size - size;
 
18
    if (inc) return (blocks + 1) * block_size;
 
19
    return size;
 
20
}
 
21
 
 
22
int main(int argc, char *argv[]) {
 
23
    int err;
 
24
    long i;
 
25
    size_t size = DEFAULT_SIZE;
 
26
    size_t iterations = ITERATIONS;
 
27
    int standard_memory = 0;
 
28
    unsigned long res;
 
29
    
 
30
    size_t runtime;
 
31
    size_t us;
 
32
    struct timeval tv1,tv2;
 
33
 
 
34
    char *name, fname[255];
 
35
    FILE *f;
 
36
 
 
37
    name = strrchr(argv[0], '/');
 
38
    if (name) name += 1;
 
39
    else name = argv[0];
 
40
 
 
41
    if (argc > 1) {
 
42
        size = atoi(argv[1]);
 
43
    }
 
44
    
 
45
    if (argc > 2) {
 
46
        iterations = atoi(argv[2]);
 
47
        if (!iterations) iterations = 1;
 
48
    }
 
49
    
 
50
    size *= 1000000;
 
51
 
 
52
    if (exercise_required_alignment > 1) {
 
53
        size = get_padded_size(size, exercise_required_alignment);
 
54
    }
 
55
 
 
56
    setlocale(LC_NUMERIC, "en_US");
 
57
    printf("Computing pi using %'lum throws of monte carlo, Iterations %u\n", size/1000000, iterations);
 
58
 
 
59
    err = exercise_init(name, size);
 
60
    if (err) return err;
 
61
 
 
62
    gettimeofday(&tv1, NULL);
 
63
    runtime = exercise(&res, size, iterations);
 
64
    gettimeofday(&tv2, NULL);
 
65
 
 
66
    if (runtime == (size_t)-1) {
 
67
        return 1;
 
68
    }
 
69
 
 
70
    printf("Result: %lf (should 3.14159265358979323846)\n", 4. * res / size);
 
71
 
 
72
    exercise_free();
 
73
 
 
74
    us = (tv2.tv_sec - tv1.tv_sec)*1000000 + (tv2.tv_usec - tv1.tv_usec);
 
75
    us /= iterations;
 
76
    printf("Speed: %.2lf giga-tries/sec (%lf s)\n", 0.001 * size / us, us / 1000000.);
 
77
 
 
78
    return 0;
 
79
}
 
80