您可以使用open、read 和write 调用直接测量磁盘 I/O 速度,避免自动流缓冲(如fopen)。
对于read 和write,您应该验证读取和写入的字节数。
要计时,只需使用clock_gettime(CLOCK_PROCESS_CPUTIME_ID,*tp) 或CLOCK_THREAD_CPUTIME_ID(参见this question)。我这么说是因为 Linux includes kernel/system time 代表进程(这在 clock_gettime 的 man 条目中只有 on OpenBSD 是明确的)。如果要测量连续(非突发)速度,您可能需要确保正在填充磁盘缓存,并且可能还需要填充内核磁盘页面缓存。这样您对open 的调用将仅在完成文件写入后返回。
只有使用上述过程才能获得正常使用内核磁盘页面缓存的结果。您可以进一步绕过内核页面缓存,如下所示。但请记住,这些是“原始”结果,不一定与您使用内核页面缓存时的结果相对应,正如 Basile Starynkevitch 所描述的那样。
使用O_SYNC|O_DIRECT 操作模式标志调用open(参见this question)。 O_DIRECT 绕过内核页面缓存。这样,您的数据将被确认完全传输到磁盘而不是计算机 RAM 缓存。
O_DIRECT (since Linux 2.4.10)
Try to minimize cache effects of the I/O to and from this
file. In general this will degrade performance, but it is
useful in special situations, such as when applications do
their own caching. File I/O is done directly to/from user-
space buffers. The O_DIRECT flag on its own makes an effort
to transfer data synchronously, but does not give the
guarantees of the O_SYNC flag that data and necessary metadata
are transferred. To guarantee synchronous I/O, O_SYNC must be
used in addition to O_DIRECT. See NOTES below for further
discussion.
除非我弄错了,否则您不必担心内核会在测试中将另一个进程调度到您的 CPU 上,除非您的大多数 CPU 都很忙。即使它确实安排了另一个进程,它也可能在同步写入完成后立即返回到您的进程(如果您知道,请在评论中告诉我)。因此使用CLOCK_MONOTONIC_RAW 可能无关紧要。 cpuset 可能有用。
请参阅 Linux man 条目和 GNU C 库参考手册。另请参阅 fsync 和 this question,了解页面缓存写入需要多长时间才能到达磁盘。