133 lines
2.9 KiB
C
133 lines
2.9 KiB
C
#include <stdio.h>
|
|
#include <time.h>
|
|
|
|
void fizzbuzz(int n)
|
|
{
|
|
int i;
|
|
for (i = 1; i <= n; i++)
|
|
{
|
|
if (i%3 == 0 || i%5 == 0)
|
|
{
|
|
if (i % 3 == 0 && i % 5 == 0)
|
|
printf("fizzbuzz\n");
|
|
else if (i%3==0)
|
|
printf("fizz\n");
|
|
else
|
|
printf("buzz\n");
|
|
}
|
|
else
|
|
{
|
|
printf("%d\n", i);
|
|
}
|
|
}
|
|
}
|
|
|
|
#define BUF_SIZE 1024
|
|
|
|
void fizzbuzz_fast(int n)
|
|
{
|
|
int i;
|
|
|
|
char str[BUF_SIZE];
|
|
int curr_str_pos = 0;
|
|
|
|
for (i = 1; i <= n; i++)
|
|
{
|
|
if (i % 3 == 0 || i % 5 == 0)
|
|
{
|
|
char* strToPrint;
|
|
int result;
|
|
|
|
if (i % 3 == 0 && i % 5 == 0)
|
|
{
|
|
strToPrint = "fizzbuzz\n";
|
|
}
|
|
else if (i % 3 == 0)
|
|
{
|
|
strToPrint = "fizz\n";
|
|
}
|
|
else
|
|
{
|
|
strToPrint = "buzz\n";
|
|
}
|
|
|
|
result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%s", strToPrint);
|
|
if (!(result < BUF_SIZE - curr_str_pos))
|
|
{
|
|
printf("%s", str);
|
|
curr_str_pos = 0;
|
|
result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%s", strToPrint);
|
|
}
|
|
curr_str_pos += result;
|
|
}
|
|
else
|
|
{
|
|
int result;
|
|
result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%d\n", i);
|
|
|
|
if (!(result < BUF_SIZE - curr_str_pos))
|
|
{
|
|
printf("%s", str);
|
|
curr_str_pos = 0;
|
|
result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%d\n", i);
|
|
}
|
|
curr_str_pos += result;
|
|
}
|
|
}
|
|
|
|
if (curr_str_pos != 0)
|
|
{
|
|
printf("%s", str);
|
|
}
|
|
}
|
|
|
|
void fizzbuzz_branchless(int n)
|
|
{
|
|
char *zzc[]={"fizz\n","buzz\n","fizzbuzz\n","%d\n"};
|
|
int zxc[]={3,0,0,1,0,0,2};
|
|
for (int i = 1; i < n; ++i)
|
|
{
|
|
int a=i%3==0;
|
|
int b=i%5==0;
|
|
int t=b^a;
|
|
printf(zzc[zxc[a<<2|(b<<1)|t]],i);
|
|
}
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
(void)argc;
|
|
(void)argv;
|
|
|
|
int n;
|
|
|
|
clock_t reg_start, reg_end, branchless_start, branchless_end, fast_start, fast_end;
|
|
|
|
printf("How many fizzbuzzes?: ");
|
|
int ret = scanf("%d", &n);
|
|
if (ret)
|
|
{
|
|
reg_start = clock();
|
|
fizzbuzz(n);
|
|
reg_end = clock();
|
|
|
|
branchless_start = clock();
|
|
fizzbuzz_branchless(n);
|
|
branchless_end = clock();
|
|
|
|
fast_start = clock();
|
|
fizzbuzz_fast(n);
|
|
fast_end = clock();
|
|
|
|
printf("regular time: %ld\n", reg_end - reg_start);
|
|
printf("branchless time: %ld\n", branchless_end - branchless_start);
|
|
printf("fast time: %ld\n", fast_end - fast_start);
|
|
}
|
|
else
|
|
{
|
|
printf("Invalid input\n");
|
|
}
|
|
|
|
return 0;
|
|
}
|