jeudi 3 novembre 2016

What's the most efficient way to programmatically check if the year is changed

I am trying to capture packets from the NIC and save part of the packet payload as a string.

On part of packet that must be stored is its Log Time known as SysLog. Each packets has a SysLog with the following Format:

Nov 01 03 14:50:25 TCP...[other parts of packet Payload]

As it can be seen, the packet SysLog has no Year Number. My program must be running all over the year, so I need to add Year Number to the packet SysLog and convert SysLog to epoch time. The final string that I have to store is like this:

1478175389-TCP, ….

I use the following peace of code to convert Syslog to EpochTime.

tm* tm_date = new tm();
Std ::string time = Current_Year;
time += " ";
time += packet.substr(0,18);
strptime(time.c_str(), "%Y %b %d %T", tm_date);
EpochTime = timegm(tm_date);

The currentYear Method:

std::string    currentYear() {
    std::stringstream now;
    auto tp = std::chrono::system_clock::now();
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
    size_t modulo = ms.count() % 1000;
    time_t seconds = std::chrono::duration_cast<std::chrono::seconds>(ms).count();
#if HAS_STD_PUT_TIME
#else
    char buffer[25]; // holds "2013-12-01 21:31:42"
    if (strftime(buffer, 25, "%Y", localtime(&seconds))) {
        now << buffer;
    }
#endif // HAS_STD_PUT_TIME
    return now.str();
}

The above operations are what i have to do for every packets. The packet rate is 100000-1000000 pps and the above peace of code is very time consuming specially on currentYear(). One possible optimization is to remove currentYear() Method and save the Year number as a constant value. As said earlier my program must be run all over the year and as you know 2017 is comming. We can not change our binary at 31/12/2016 23:59:00 and also we don’t want to waste our time for calculating Year Number!!

I need a more efficient way to calculate the current year number without running it for each packet.

Is it possible? What is your suggestion for me?

Aucun commentaire:

Enregistrer un commentaire