fwrite() - 大小和计数对性能的影响 [英] fwrite() - effect of size and count on performance
问题描述
关于 fwrite() 中两个参数 'size' 和 'count' 的用途似乎有很多混淆.我想弄清楚哪个会更快 -
There seems to be a lot of confusion regarding the purpose of the two arguments 'size' and 'count' in fwrite(). I am trying to figure out which will be faster -
fwrite(source, 1, 50000, destination);
或
fwrite(source, 50000, 1, destination);
这是我代码中的一个重要决定,因为此命令将执行数百万次.
This is an important decision in my code as this command will be executed millions of times.
现在,我可以直接进行测试并使用能够提供更好结果的方法,但问题是该代码适用于许多平台.
Now, I could just jump to testing and use the one which gives better results, but the problem is that the code is intended for MANY platforms.
所以,
对于跨平台哪个更好,我如何才能得到明确的答案?
How can I get a definitive answer to which is better across platforms?
fwrite() 的实现逻辑会因平台而异吗?
Will implementation logic of fwrite() vary from platform to platform?
我意识到有类似的问题(fread/fwrite 将大小和计数作为参数的基本原理是什么?,fwrite 和 write size 的性能) 但要明白这是关于同一问题的不同问题.在这种情况下,类似问题的答案是不够的.
I realize there are similar questions (What is the rationale for fread/fwrite taking size and count as arguments?, Performance of fwrite and write size) but do understand that this is a different question regarding the same issue. The answers in similar questions do not suffice in this case.
推荐答案
性能不应该依赖于任何一种方式,因为任何实现 fwrite 的人都会乘以 size 和 count 来确定要执行多少 I/O.
The performance should not depend on either way, because anyone implementing fwrite would multiply size and count to determine how much I/O to do.
以 FreeBSD 的 fwrite.c
的 libc 实现为例,它完整地读取(省略了包含指令):
This is exemplified by FreeBSD's libc implementation of fwrite.c
, which in its entirety reads (include directives elided):
/*
* Write `count' objects (each size `size') from memory to the given file.
* Return the number of whole objects written.
*/
size_t
fwrite(buf, size, count, fp)
const void * __restrict buf;
size_t size, count;
FILE * __restrict fp;
{
size_t n;
struct __suio uio;
struct __siov iov;
/*
* ANSI and SUSv2 require a return value of 0 if size or count are 0.
*/
if ((count == 0) || (size == 0))
return (0);
/*
* Check for integer overflow. As an optimization, first check that
* at least one of {count, size} is at least 2^16, since if both
* values are less than that, their product can't possible overflow
* (size_t is always at least 32 bits on FreeBSD).
*/
if (((count | size) > 0xFFFF) &&
(count > SIZE_MAX / size)) {
errno = EINVAL;
fp->_flags |= __SERR;
return (0);
}
n = count * size;
iov.iov_base = (void *)buf;
uio.uio_resid = iov.iov_len = n;
uio.uio_iov = &iov;
uio.uio_iovcnt = 1;
FLOCKFILE(fp);
ORIENT(fp, -1);
/*
* The usual case is success (__sfvwrite returns 0);
* skip the divide if this happens, since divides are
* generally slow and since this occurs whenever size==0.
*/
if (__sfvwrite(fp, &uio) != 0)
count = (n - uio.uio_resid) / size;
FUNLOCKFILE(fp);
return (count);
}
这篇关于fwrite() - 大小和计数对性能的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!