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).
There's no difference for musl or glibc, or the FreeBSD libc since they all call an underlying function with size*nmemb:
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);
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);
n = count * size;
// ...
uio.uio_resid = iov.iov_len = n;
// ...
if (__sfvwrite(fp, &uio) != 0)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With