Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If one can choose to fwrite() 100 1 bytes, or 1 100 bytes, which approach should be prefered?

Tags:

c

I am interested if there is a theoretical speed difference between

fwrite(str , 1 , 100 , fp );

and

fwrite(str , 100 , 1 , fp );

based on how the function is written in glibc, and how many write calls it makes and how it is buffered (disregarding hardware differences on gcc).

like image 906
devgirl05 Avatar asked Nov 18 '25 10:11

devgirl05


2 Answers

There's no difference for musl or glibc, or the FreeBSD libc since they all call an underlying function with size*nmemb:

musl

size_t fwrite(const void *restrict src, size_t size, size_t nmemb, FILE *restrict f)
{
    size_t k, l = size*nmemb;
    // ...
    k = __fwritex(src, l, f);

glibc

size_t
_IO_fwrite (const void *buf, size_t size, size_t count, FILE *fp)
{
  size_t request = size * count;
  // ...
  written = _IO_sputn (fp, (const char *) buf, request);

freebsd

    n = count * size;
    // ...
    uio.uio_resid = iov.iov_len = n;
    // ...
    if (__sfvwrite(fp, &uio) != 0)
like image 140
AKX Avatar answered Nov 20 '25 02:11

AKX


I wrote 2 pieces of code to examine the difference between their performance.

a.c:

#include <stdlib.h>
#include <stdio.h>

int
main() {

        char* str = "Hello\n";
        FILE* fd = fopen("out.txt", "w");
        for (int i=0; i<1000; i++) 
                fwrite(str , 1 , 100 , fd);

        fclose(fd);
        return 0;

}

b.c:

#include <stdlib.h>
#include <stdio.h>

int
main() {

        char* str = "Hello\n";
        FILE* fd = fopen("out.txt", "w");
        for (int i=0; i<1000; i++) 
                fwrite(str , 100 , 1 , fd);
        fclose(fd);
        return 0;
}

Output:


([email protected]@U-Riahi:cplay) > gcc a.c
([email protected]@U-Riahi:cplay) > time ./a.out 

real    0m0.001s
user    0m0.001s
sys 0m0.000s
([email protected]@U-Riahi:cplay) > gcc b.c
([email protected]@U-Riahi:cplay) > time ./a.out 

real    0m0.001s
user    0m0.000s
sys 0m0.001s

There no real difference between them.

like image 40
Amir reza Riahi Avatar answered Nov 20 '25 00:11

Amir reza Riahi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!