我使用下面的代碼將一個文件複製與大小約1.1 GB什麼是計算「在Linux上使用C++複製二進制文件」所消耗時間的最佳方法?
#include <iostream>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <ctime>
using namespace std;
int main()
{
clock_t start, end;
start = clock();
int read_fd;
int write_fd;
struct stat stat_buf;
off_t offset = 0;
/* Open the input file. */
read_fd = open ("source", O_RDONLY);
/* Stat the input file to obtain its size. */
fstat (read_fd, &stat_buf);
/* Open the output file for writing, with the same permissions as the
source file. */
write_fd = open ("destination", O_WRONLY | O_CREAT, stat_buf.st_mode);
/* Blast the bytes from one file to the other. */
sendfile (write_fd, read_fd, &offset, stat_buf.st_size);
/* Close up. */
close (read_fd);
close (write_fd);
end = clock();
cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
cout << "CPU-TIME START " << start << "\n";
cout << "CPU-TIME END " << end << "\n";
cout << "CPU-TIME END - START " << end - start << "\n";
cout << "TIME(SEC) " << static_cast<double>(end - start)/CLOCKS_PER_SEC << "\n";
return 0;
}
輸出是:
CLOCKS_PER_SEC 1000000
CPU-TIME START 0 CPU-TIME END 6140000
CPU-TIME END - START 6140000 TIME(SEC) 6.14
但是,當我實際計算時,它(複製)需要時間約84 SEC !!! 現在我將在下面的代碼中使用「結構timeval」,輸出爲:83 456677
它與實際時間幾乎相同。
#include <iostream>
#include <sys/sendfile.h> // sendfile
#include <fcntl.h> // open
#include <unistd.h> // close
#include <sys/stat.h> // fstat
#include <sys/types.h> // fstat
#include <ctime>
extern "C" {
#include <sys/time.h>
}
#include <stdio.h>
using namespace std;
int main() {
struct timeval diff, startTV, endTV;
gettimeofday(&startTV, NULL);
int source = open("source", O_RDONLY, 0);
int dest = open("distination", O_WRONLY | O_CREAT /*| O_TRUNC/*/, 0644);
// struct required, rationale: function stat() exists also
struct stat stat_source;
fstat(source, &stat_source);
sendfile(dest, source, 0, stat_source.st_size);
close(source);
close(dest);
gettimeofday(&endTV, NULL);
timersub(&endTV, &startTV, &diff);
printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
return 0;
}
然後,我將使用「PV源> destination'a命令時輸出爲:1.02e+03MB 0:01:24 [12.1MB/s] [===========================>] 100%
和它與實際的時間相同。
而且,當我在模式圖形(複製/粘貼普通)中複製文件需要大約84秒的時間。
問題
- 什麼是在第一時間的方式計算?
- 'pv'或Pipe Viewer是否正確顯示操作系統「複製文件所耗費的時間」?
- 得出結論,我們通過sendfile()複製的時間與OS幾乎相同?
此網站上查看許多與會者/讀取標籤的問題。我把你的C++標籤改爲C. –
@CaptainGiraffe他使用'iostream'和'ctime'頭......這是C++代碼,儘管他正在做的大部分都是C. –
@SchighSchagh Mea culpa,謝謝。我重新添加了C++標籤。 OP,當你說你計算你的意思是你看你的手錶的時間是正確的? –