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

huangapple go评论54阅读模式
英文:

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

问题

fwrite(str , 1 , 100 , fp );

fwrite(str , 100 , 1 , fp );
这两者之间是否存在理论上的速度差异,取决于glibc中函数的编写方式,以及它调用了多少次写操作以及它的缓冲方式(不考虑gcc上的硬件差异)。

英文:

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

答案1

得分: 7

我明白了,我将只翻译代码部分:

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)
英文:

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)

答案2

得分: 1

a.cb.c 的代码差异在于 fwrite 函数中的参数顺序。然而,在性能上,这两个版本没有实际区别。

英文:

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:


(a.riahi@asax.local@U-Riahi:cplay) > gcc a.c
(a.riahi@asax.local@U-Riahi:cplay) > time ./a.out 

real	0m0.001s
user	0m0.001s
sys	0m0.000s
(a.riahi@asax.local@U-Riahi:cplay) > gcc b.c
(a.riahi@asax.local@U-Riahi:cplay) > time ./a.out 

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

There no real difference between them.

huangapple
  • 本文由 发表于 2023年4月17日 19:17:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定