最近在琢磨一个日志类,然后就想到,如果处于一个频繁写日志的状态,那么IO操作会不会引起瓶颈呢。
于是就做了一个测试。
有一个4000容量的字符数组,比较一个一个写,和一次性写所花的时间,执行200次。
结果显示,一个一个写的话,时间需要 617.426s
一次性一次性的写的话,时间需要0.131s
总结,合理使用缓存,可以提高程序性能。
#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");
}