Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- #define NUM_RUNS 500
- void fizzbuzz_normal ()
- {
- int i, a, b;
- for (i = 1; i <= 100; i++)
- {
- a = i % 5;
- b = i % 3;
- if (a && b)
- printf("%d\n", i);
- else if (a)
- puts("fizz");
- else if (b)
- puts("buzz");
- else
- puts("fizzbuzz");
- }
- }
- void fizzbuzz_normal_15 ()
- {
- int i, a, b;
- for (i = 1; i <= 100; i++)
- {
- if (i % 15)
- printf("%d\n", i);
- else if (i % 5)
- puts("fizz");
- else if (i % 3)
- puts("buzz");
- else
- puts("fizzbuzz");
- }
- }
- void fizzbuzz_buffered ()
- {
- int i, a, b;
- char buffer[9 * 100 + 1];
- char* ptr = buffer;
- for (i = 1; i <= 100; i++)
- {
- a = i % 5;
- b = i % 3;
- if (a && b)
- ptr += sprintf(ptr, "%d\n", i);
- else if (a)
- {
- strcpy(ptr, "fizz\n");
- ptr += 5;
- }
- else if (b)
- {
- strcpy(ptr, "buzzz\n");
- ptr += 5;
- }
- else
- {
- strcpy(ptr, "fizzbuzz\n");
- ptr += 9;
- }
- }
- fputs(buffer, stdout);
- }
- typedef void (*func_t)();
- void time_func (double* out, func_t func)
- {
- clock_t start, end;
- start = clock();
- int i;
- for (i = 0; i < NUM_RUNS; i++)
- func();
- end = clock();
- *out = (end - start) / (double)CLOCKS_PER_SEC;
- }
- int main ()
- {
- double time_normal,
- time_normal_15,
- time_buffered;
- time_func(&time_normal, fizzbuzz_normal);
- time_func(&time_normal_15, fizzbuzz_normal_15);
- time_func(&time_buffered, fizzbuzz_buffered);
- printf("\n"
- "results:\n"
- " normal %.4fs\n"
- " normal (i %% 15) %.4fs\n"
- " buffered %.4fs\n",
- time_normal,
- time_normal_15,
- time_buffered);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement