面试题答案
一键面试性能优化方法
- 使用合适的缓冲区大小:选择一个合适的缓冲区大小可以减少系统调用次数。过小的缓冲区会导致频繁的读写操作,而过大的缓冲区可能会浪费内存。通常,几KB到几十KB的缓冲区大小比较合适。
- 分块读写:将大文件分成多个较小的块进行读写,避免一次性读取或写入整个大文件,降低内存压力。
- 减少不必要的操作:在读写过程中,尽量减少在循环内的不必要计算和操作,以提高效率。
优化后的代码示例
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024 * 1024 // 1MB缓冲区大小
int main() {
FILE *srcFile = fopen("large_file.bin", "rb");
FILE *dstFile = fopen("new_large_file.bin", "wb");
if (!srcFile ||!dstFile) {
perror("Failed to open files");
return 1;
}
int *buffer = (int *)malloc(BUFFER_SIZE * sizeof(int));
if (!buffer) {
perror("Failed to allocate memory");
fclose(srcFile);
fclose(dstFile);
return 1;
}
size_t readBytes;
while ((readBytes = fread(buffer, sizeof(int), BUFFER_SIZE, srcFile)) > 0) {
fwrite(buffer, sizeof(int), readBytes, dstFile);
}
free(buffer);
fclose(srcFile);
fclose(dstFile);
return 0;
}
在上述代码中:
- 定义了一个
BUFFER_SIZE
为1MB的缓冲区大小。 - 使用
malloc
分配缓冲区内存。 - 在
while
循环中,每次从源文件读取BUFFER_SIZE
大小的数据块,并将其写入目标文件,直到读取完整个源文件。 - 最后释放缓冲区内存并关闭文件。