gpt4 book ai didi

c - C 中的文件系统 VS 原始磁盘基准测试

转载 作者:行者123 更新时间:2023-12-02 04:50:47 25 4
gpt4 key购买 nike

我正在做一些基准测试(在 OS X 上)以了解文件系统的使用如何影响带宽等。我正在使用并发,希望在 FS 中创建碎片。

但是,看起来使用 FS 比原始磁盘访问更有效。为什么?

这是我的代码:

#include <pthread.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define NO_THREADS (2)
#define PACKET_SIZE (1024 * 4)
#define SIZE_TO_WRITE (1024 * 1024 * 1024)

void write_buffer(void *arg) {
int *p_start = arg;
int start = *p_start;
char buffer[PACKET_SIZE];


char path[50];
sprintf(path, "file%d", start);
int fd = open(path, O_CREAT | O_WRONLY | O_APPEND);

//int fd = open("/dev/rdisk0s4", O_WRONLY);

if (fd < 0) {
fprintf(stderr, "Cound not open.\n", stderr);
goto end;
}

//lseek(fd, start * SIZE_TO_WRITE, SEEK_SET);

int current;
for (current = start; current < start + SIZE_TO_WRITE; current += PACKET_SIZE) {

int i;
for (i = 0; i < PACKET_SIZE; ++i) {
buffer[i] = i + current;
}

if (PACKET_SIZE != write(fd, buffer, PACKET_SIZE)) {
fprintf(stderr, "Could not write packet %d properly.", current);
goto close;
}
}

fsync(fd);

close:
close(fd);
end:
pthread_exit(0);
}

void flush(void) {
fflush(stdout);
fflush(stderr);
}

int main(void) {
pthread_t threads[NO_THREADS];
int starts[NO_THREADS];
int i;

atexit(flush);

for (i = 0; i < NO_THREADS; ++i) {

starts[i] = i;

if(pthread_create(threads + i, NULL, (void *) &write_buffer, (void *)(starts + i))) {
fprintf(stderr, "Error creating thread no %d\n", i);
return EXIT_FAILURE;
}
}

for (i = 0; i < NO_THREADS; ++i) {
if(pthread_join(threads[i], NULL)) {
fprintf(stderr, "Error joining thread\n");
return EXIT_FAILURE;
}
}

puts("Done");

return EXIT_SUCCESS;
}

在 FS 的帮助下,2 个线程在 31.33 秒内写入文件。没有,几分钟后就实现了...

最佳答案

当您使用 /dev/rdisk0s4 而不是 /path/to/normal/file%d 时,对于您执行的每次写入,操作系统都会发出一个磁盘 I/欧。即使该磁盘是 SSD,这也意味着往返时间可能至少平均为几百微秒。相反,当您写入文件时,文件系统直到稍后才真正将您的写入发出到磁盘。 Linux man page很好地描述了这一点:

A successful return from write() does not make any guarantee that data has been committed to disk. In fact, on some buggy implementations, it does not even guarantee that space has successfully been reserved for the data. The only way to be sure is to call fsync(2) after you are done writing all your data.

因此,您写入的数据正在由文件系统缓冲,这只需要在内存中制作一个副本——这可能最多需要几微秒的时间。如果您想进行同类比较,您应该确保对两个测试用例进行同步 I/O。即使在整个测试完成后运行 fsync 也可能会让文件系统更快,因为它将 I/O 批量化为一个连续的流式写入,这可能比直接测试更快在磁盘上可以实现。

一般来说,编写良好的系统基准测试非常困难,尤其是当您对要测试的系统知之甚少时。很多。如果您想要高质量的结果,我建议您使用现成的 Unix 文件系统基准测试工具包——否则,您可能会花费一生的时间来学习您正在测试的操作系统和文件系统的性能问题……不是那样的坏事,如果你像我一样对它感兴趣:-)

关于c - C 中的文件系统 VS 原始磁盘基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com