Last active 1 year ago

mga's Avatar mga revised this gist 1 year ago. Go to revision

1 file changed, 52 insertions

speed.c(file created)

@@ -0,0 +1,52 @@
1 + #include <gmp.h>
2 + #include <stdio.h>
3 + #include <stdlib.h>
4 + #include <time.h>
5 +
6 + int main(int argc, char *argv[]) {
7 + // Get the limit from the first argument
8 + if (argc != 2) {
9 + printf("Wrong input.\n");
10 + printf("Usage: howfast <limit>\n");
11 + return EXIT_FAILURE;
12 + }
13 +
14 + long int limit = strtol(argv[1], NULL, 10);
15 +
16 + // Setup GMP arithmetic library
17 + mpz_t a;
18 + mpz_t b;
19 + mpz_t c;
20 +
21 + mpz_init_set_ui(a, 1);
22 + mpz_init_set_ui(b, 0);
23 + mpz_init(c);
24 +
25 + // Start timer
26 + const clock_t start = clock();
27 +
28 + // Fibonacci calculation
29 + for (long int i = 0; i < limit; ++i) {
30 + mpz_add(c, a, b);
31 + mpz_set(a, b);
32 + mpz_set(b, c);
33 + }
34 +
35 + // End timer
36 + const clock_t end = clock();
37 +
38 + // Print the result
39 + printf("Fibonacci number %ld: ", limit);
40 + mpz_out_str(stdout, 10, b);
41 + printf("\n");
42 +
43 + // Clean up
44 + mpz_clear(a);
45 + mpz_clear(b);
46 + mpz_clear(c);
47 +
48 + // Print time
49 + double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
50 + printf("Time: %f seconds\n", time_taken);
51 + return EXIT_SUCCESS;
52 + }
Newer Older