前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >在文件IO操作中,合理使用缓存。

在文件IO操作中,合理使用缓存。

作者头像
forxtz
发布2020-10-10 16:41:30
发布2020-10-10 16:41:30
1.6K00
代码可运行
举报
文章被收录于专栏:源懒由码源懒由码
运行总次数:0
代码可运行

最近在琢磨一个日志类,然后就想到,如果处于一个频繁写日志的状态,那么IO操作会不会引起瓶颈呢。

于是就做了一个测试。

有一个4000容量的字符数组,比较一个一个写,和一次性写所花的时间,执行200次。

结果显示,一个一个写的话,时间需要 617.426s

     一次性一次性的写的话,时间需要0.131s

总结,合理使用缓存,可以提高程序性能。

代码语言:javascript
代码运行次数:0
运行
复制
#include <iostream>
#include <direct.h>
#include <iomanip>
#include <fstream>
#include <memory>
using namespace std;

std::string printf_gmtime(time_t t){
    std::string ts = std::asctime(gmtime(&t));
    ts.resize(ts.size()-1);    //skip trailing newline
    return ts;
}

std::string printf_loacltime(time_t t){
    // equal ctime(&t);
    std::string ts = std::asctime(localtime(&t));
    ts.resize(ts.size()-1);    //skip trailing newline
    return ts;
}

void printf_cpudifftime(time_t st){
    clock_t en = clock();
    //cout << difftime(en,st) << endl;
    cout<< "Running time is: "<<difftime(en,st)/CLOCKS_PER_SEC<<"s"<<endl;
}

const string filename1 = "test1.log";
const string filename2 = "test2.log";

char data[4000];

int main(){
    for(int i = 0; i<4000;i++){
        data[i] = i%96+32;
    }
    data[3999] = '\0';
    cout << data << endl;
    clock_t s;

    s = clock();
    for( int i = 0; i < 200; i++){
        for( int j = 0;data[j] !='\0';j++){
            ofstream file(filename1.c_str(),std::ios::out | std::ios::app);
            file << data[j];
        }
    }
    printf_cpudifftime(s);

    s = clock();
    for( int i = 0; i < 200; i++){
            ofstream file(filename2.c_str(),std::ios::out | std::ios::app);
            file << data;
    }
    printf_cpudifftime(s);

    system("pause");
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-09-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档