利用fstream进行文件拷贝测试

今天翻到一个早期写测试代码的目录,找到几个以前的测试代码,于是拿出来贴到博客中。(只是简单的测试,并不严谨。注意这里windows和linux的硬件环境不一样)

这一个是使用fstream进行文件拷贝的代码,测试机器的环境大概如下(时间久了,机器有更新)

CPU: i7 低压版
硬盘:两个60G的SSD,好像是建兴的
内存:8G DDR3

当时仅在Arch Linux上做了测试,今天顺便在windows下做一个测试。
CentOS7_gcc4.9.4.ova其实是虚拟机的镜像文件,1.8G大小。

代码如下:

#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>

bool copy_file(const char* src_file_path,const char* dst_file_path)
{
    // 检测目标文件是否存在
    {
        std::ifstream exsit(dst_file_path);
        if(exsit){
            std::cout<<"目标文件 "<< dst_file_path<< " 已经存在"<<std::endl;
            return false;
        }
    }

    std::ifstream fin(src_file_path,std::ios::binary);
    std::ofstream fout(dst_file_path,std::ios::binary);
    if(!fin || !fout){
        std::cout<<"打开源文件或目标文件失败"<<std::endl;
        return false;
    }
    // rdbuf返回streambuf*
    // 速度比迭代器拷贝快太多
    // Linux下测试结果
        // time ./fstream_copy_file.exe CentOS7_gcc4.9.4.ova /mnt/data/CentOS7_gcc4.9.4.ova
        //  0.23s user 8.15s system 10% cpu 1:16.98 total
    fout << fin.rdbuf();
    return true;

    /*
    使用迭代器进行拷贝没有大问题,但是效率不高
    // time ./fstream_copy_file.exe CentOS7_gcc4.9.4.ova /mnt/data/CentOS7_gcc4.9.4.ova
        407.45s user 4.37s system 97% cpu 7:00.73 total

    fin.unsetf(std::ios::skipws);   //输入流默认跳过空白字符,取消此设置
    // 使用迭代器进行拷贝
    std::copy(std::istream_iterator<char>(fin),
              std::istream_iterator<char>(),
              std::ostream_iterator<char>(fout,""));
    return true;
    */
}

int main(int c,char** v)
{
    if(c != 3){
        printf("Usage:%s srcfile dstfile\n",v[0]);
        return 0;
    }
    copy_file(v[1],v[2]);
    return 0;
}

测试结果如下:
Windows 10
Windows下使用VS2015编译,64位版本(time命令来自git-bash)
Windows下硬盘是两个机械硬盘之间拷贝(1T 7200转希捷)

# 使用rdbuf拷贝,速度大概50M每秒
$ time ./fstrean_copy_file.exe /g/CentOS7_gcc4.9.4.ova /d/CentOS7_gcc4.9.4.ova

real    0m36.357s
user    0m0.000s
sys     0m0.015s

# 使用std::copy拷贝,速度大概6M每秒
$ time ./fstrean_copy_file.exe /g/CentOS7_gcc4.9.4.ova /d/CentOS7_gcc4.9.4.ova

real    5m3.663s
user    0m0.000s
sys     0m0.015s

猜你喜欢

转载自www.cnblogs.com/oloroso/p/8979507.html