C++ write and read file via fstream and time cost

#include <iostream>
#include <uuid/uuid.h>
#include <ctime>
#include <fstream>
#include <sstream>
#include <chrono>
#include <string.h>

using namespace std;

void retrieveUuid1(char *uuidValue);
char *getTimeNow();
void writeFile3();
void readFile4();

int main()
{
    writeFile3();
    return 0;
}

void readFile4()
{
    fstream rFile("log.txt",ios::in);
    if(!rFile.is_open())
    {
        cout<<"Open log.txt failed!"<<endl;
    }

    string line;
    unsigned num=0;
    while(getline(rFile,line))
    {
        ++num;
        if(num%1000000==0)
        {
            cout<<"Num is "<<num<<",value is "<<line<<",now is "<<getTimeNow()<<endl;
        }
    }
    rFile.close();
    cout<<"Now finished in openLog4() and now is "<<getTimeNow()<<endl;
}

void writeFile3()
{
    fstream wFile("log.txt",ios::app|ios::out);
    if(!wFile.is_open())
    {
        cout<<"Create or open log.txt failed!"<<endl;
    }

    unsigned num=0;
    stringstream ss;
    char *uuidValue=(char*)malloc(40);
    unsigned int loops=100;
    unsigned int loopTimes=1000000;
    string str; 
    chrono::time_point<chrono::system_clock> startTime;
    chrono::time_point<chrono::system_clock> endTime;
    for(int i=0;i<loops;i++)
    {
        startTime=chrono::system_clock::now();
        for(int j=0;j<loopTimes;j++)
        {
            ++num;
            retrieveUuid1(uuidValue);
            str=to_string(num); 
            str.append(",");
            str.append(uuidValue);  
            ss<<str<<endl;
        }
        wFile<<ss.str()<<endl;
        ss=stringstream();
        endTime=chrono::system_clock::now();        
        cout<<"Num is "<<num<<",now is "<<getTimeNow()<<endl;
        cout<<"Time cost "
            <<chrono::duration_cast<chrono::seconds>(endTime-startTime).count()<<" seconds,"
            <<chrono::duration_cast<chrono::milliseconds>(endTime-startTime).count()<<" milliseconds,"
            <<chrono::duration_cast<chrono::microseconds>(endTime-startTime).count()<<" microseconds,"
            <<chrono::duration_cast<chrono::nanoseconds>(endTime-startTime).count()<<" nanoseconds"<<endl<<endl;
    }

    free(uuidValue);
    wFile.close();
    cout<<"Finished in log3() and now is "<<getTimeNow()<<endl;    
}

void retrieveUuid1(char *uuidValue)
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID,uuidValue);
}

char *getTimeNow()
{
    char *dtValue=(char*)malloc(20);
    time_t rawTime=time(NULL);
    struct tm tmInfo=*localtime(&rawTime);
    strftime(dtValue,20,"%Y%m%d%H%M%S",&tmInfo);
    return dtValue;
}

Compile

g++ -g -std=c++2a -I. h1.cpp -o h1 -luuid

Run 

 

posted @ 2021-12-20 11:34  FredGrit  阅读(44)  评论(0编辑  收藏  举报