简体   繁体   中英

speed of fprintf() vs. fwrite()

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

ie 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);
}

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM