#ifndef TEST_H
#define TEST_H
int grey();
int add(int a, int b);
int SobelTest();
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/sendfile.h>
using namespace std;
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
int fileCopy() {
// printf("hello \n");
auto start_time = high_resolution_clock::now();
// 打开源文件
int source_fd = open("/data/local/tmp/hello.exe", O_RDONLY);
if (source_fd == -1) {
cout << "无法打开源文件" << endl;
return -1;
}
// 打开目标文件
int target_fd = open("/data/local/tmp/target.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (target_fd == -1) {
cout << "无法打开目标文件" << endl;
return -1;
}
// 使用sendfile复制文件
off_t offset = 0;
struct stat stat_buf;
fstat(source_fd, &stat_buf);
ssize_t bytes_sent = sendfile(target_fd, source_fd, &offset, stat_buf.st_size);
if (bytes_sent == -1) {
cout << "复制文件时出错" << endl;
return -1;
}
// 关闭文件
close(source_fd);
close(target_fd);
cout << "文件已复制" << endl;
// 获取当前时间点
auto end_time = high_resolution_clock::now();
// 计算时间差
auto duration = duration_cast<milliseconds>(end_time - start_time);
cout << "代码执行时间:" << duration.count() << " 毫秒" << endl;
return 0;
}
char buffer[10*1024*1024];
int fileCopy2() {
// printf("hello \n");
auto start_time = high_resolution_clock::now();
// 打开源文件
int source_fd = open("/data/local/tmp/hello.exe", O_RDONLY);
if (source_fd == -1) {
cout << "无法打开源文件" << endl;
return -1;
}
// 打开目标文件
int target_fd = open("/data/local/tmp/target.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (target_fd == -1) {
cout << "无法打开目标文件" << endl;
return -1;
}
// 读写数据
ssize_t bytes_read;
while ((bytes_read = read(source_fd, buffer, sizeof(buffer))) > 0) {
ssize_t bytes_written = write(target_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
cout << "写入数据时出错" << endl;
return -1;
}
}
// 关闭文件
close(source_fd);
close(target_fd);
cout << "文件已复制" << endl;
// 获取当前时间点
auto end_time = high_resolution_clock::now();
// 计算时间差
auto duration = duration_cast<milliseconds>(end_time - start_time);
cout << "代码执行时间2:" << duration.count() << " 毫秒" << endl;
return 0;
}
#endif
sendfile和 read/write性能对比
于 2023-03-29 23:06:43 首次发布