sendfile和 read/write性能对比

#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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值