[英]I made program that copies data from one file and pastes to another using (read,write) but i think its taking too long
i need to copy 1gb file to another and i am using this code while using different buffers (1byte, 512byte and 1024byte) while using 512byte buffer it took me about 22seconds but when i use 1byte buffer copying doesnt end even after 44minutes.我需要将 1gb 文件复制到另一个文件,我在使用不同的缓冲区(1 字节、512 字节和 1024 字节)时使用此代码,而使用 512 字节缓冲区大约需要 22 秒,但是当我使用 1 字节缓冲区复制时,即使在 44 分钟后也不会结束。 Is that time expected or mby something is wrong with my code
那个时间是预期的还是我的代码有问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <corecrt_io.h>
int main(int argc, char* argv[])
{
char sourceName[20], destName[20], bufferStr[20];
int f1, f2, fRead;
int bufferSize = 0;
char* buffer;
/*printf("unesite buffer size(u bytima): ");
scanf("%d", &bufferSize);*/
//bufferSize = argv[3];
bufferSize = atoi(argv[3]);
buffer = (char*)calloc(bufferSize, sizeof(char));
/*printf("unesite source name: ");
scanf("%s", sourceName);*/
strcpy(sourceName, argv[1]);
f1 = open(sourceName, O_RDONLY);
if (f1 == -1)
printf("something's wrong with oppening source file!\n");
else
printf("file opened!\n");
/*printf("unesite destination name: ");
scanf("%s", destName);*/
strcpy(destName, argv[2]);
f2 = open(destName, O_CREAT | O_WRONLY | O_TRUNC | O_APPEND);
if (f2 == -1)
printf("something's wrong with oppening destination file!\n");
else
printf("file2 opened!");
fRead = read(f1, buffer, bufferSize);
while (fRead != 0)
{
write(f2, buffer, bufferSize);
fRead = read(f1, buffer, bufferSize);
}
return 0;
}
Yes, this is expected, because system calls are expensive operations, so the time is roughly proportional to the number of times you call read()
and write()
.是的,这是意料之中的,因为系统调用是昂贵的操作,所以时间大致与调用
read()
和write()
的次数成正比。 If it takes 22 seconds to copy with 512-byte buffers, you should expect it to take about 22 * 512
seconds with 1-byte buffers.如果使用 512 字节缓冲区进行复制需要 22 秒,那么使用 1 字节缓冲区需要大约
22 * 512
秒。 That's 187 minutes, or over 3 hours.那是 187 分钟,或超过 3 个小时。
This is why stdio
implements buffered output by default.这就是
stdio
默认实现缓冲输出的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.