spaces.c
text/plain
#include <time.h>
#include <stdio.h>
#include <string.h>
int f1(char *data, int count)
{
int len = 0;
/* OK, append the spaces */
while (--count >= 0)
data[len++] = ' ';
data[len] = '\0';
return len;
}
int f2(char *data, int count)
{
memset(data, ' ', count);
data[count] = '\0';
return count;
}
#define NLOOPS 100000000
int main(void)
{
char buffer[8];
clock_t start, end;
unsigned long long x = 0;
start = clock();
for (int i = 0; i < NLOOPS; i++)
{
x += f1(buffer, sizeof(buffer) - 1);
}
end = clock();
printf("while %g seconds\n", (double) (end - start) / CLOCKS_PER_SEC);
start = clock();
for (int i = 0; i < NLOOPS; i++)
{
x += f2(buffer, sizeof(buffer) - 1);
}
end = clock();
printf("memset %g seconds\n", (double) (end - start) / CLOCKS_PER_SEC);
printf("%lld\n", x);
return 0;
}