英文:
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.c
和 b.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论