Reputation: 1317
I have seen it stated in several places that an fprintf() operation is a bit slower that an fwrite() operation, due to the extra formatting operations in fprintf. I wanted to see if I could actually test this so I have some sample code below which (I believe) does just that. results are of course always a little different, however the majority of the time they are something like this:
Avg. no. of ticks per fwrite() over 1000000 writes: 0.2000
Avg. no. of ticks per fprintf() over 1000000 writes: 0.1300
i.e. fwrite() seems to be actually a little bit slower that fprintf(). So my question here is two-fold:
A. looking at the code (below) I used to test this, is this a reasonable method to test
such a thing? can anyone speculate wether the results it yields are in anyway way an
accurate representation of how long each operation actually takes (in terms of
ticks)?
B. If so, why is it that fwrite() takes longer when I would assume that fprintf() has effectively more work with the formatting?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define NO_OF_WRITES 1000000
int main()
{
clock_t start1, end1, start2, end2;
FILE *fp;
int i;
float avg;
float diffs = 0;
uint8_t byte = 0x30;
if ((fp = fopen("file.bin", "w")) == NULL)
{
printf("Error opening file for writing");
exit(-1);
}
for (i = 0; i < NO_OF_WRITES; i++)
{
start1 = clock();
fwrite(&byte, 1, 1, fp);
end1 = clock();
diffs += (end1 - start1);
}
avg = diffs / NO_OF_WRITES;
printf("Avg. no. of ticks per fwrite() over %d writes: %.4f\n", NO_OF_WRITES, avg);
diffs = 0;
for (i = 0; i < NO_OF_WRITES; i++)
{
start2 = clock();
fprintf(fp, "%c", byte);
end2 = clock();
diffs += (end2 - start2);
}
avg = diffs / NO_OF_WRITES;
printf("Avg. no. of ticks per fprintf() over %d writes: %.4f\n", NO_OF_WRITES, avg);
fclose(fp);
}
Upvotes: 0
Views: 8954
Reputation: 126175
Since you're testing writes of a single character, it is likely that other overhead is dominating. In particular, fwrite
takes two arguments that it multiplies together to determine the total size to write, and it is likely that that single multiply instruction is dominating the time needed by fwrite
...
Upvotes: 1
Reputation: 9
http://bobobobo.wordpress.com/2008/02/07/speed-tests-fprintf-vs-ofstream-and-fprintf-vs-fwrite/
I think this would solve your problem
Upvotes: 0