Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, fastest way to get milliseconds since midnight [closed]

Tags:

c++

time

This is code that will run often and have to run fast so I'd like to get some opinions on what the quickest implementation is. Note, I actually need the full millisecond resolution to some degree of accuracy (so seconds * 1000 does not suffice). For this project, using Boost is OK.

EDIT: The target platform is x64_86 CentOS5, also, hoping to be able to rely on the OS clock so I can also use this in a program that is not running continuously.

like image 297
user788171 Avatar asked Jun 20 '12 15:06

user788171


2 Answers

C++ has the chrono library for dealing with time:

#include <chrono>
#include <iostream>
#include <ctime>

std::chrono::system_clock::duration duration_since_midnight() {
    auto now = std::chrono::system_clock::now();

    time_t tnow = std::chrono::system_clock::to_time_t(now);
    tm *date = std::localtime(&tnow);
    date->tm_hour = 0;
    date->tm_min = 0;
    date->tm_sec = 0;
    auto midnight = std::chrono::system_clock::from_time_t(std::mktime(date));

    return now-midnight;
}

int main()
{
    auto since_midnight = duration_since_midnight();

    auto hours = std::chrono::duration_cast<std::chrono::hours>(since_midnight);
    auto minutes = std::chrono::duration_cast<std::chrono::minutes>(since_midnight - hours);
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(since_midnight - hours - minutes);
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(since_midnight - hours - minutes - seconds);
    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(since_midnight - hours - minutes - seconds - milliseconds);
    auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(since_midnight - hours - minutes - seconds - milliseconds - microseconds);

    std::cout << hours.count() << "h ";
    std::cout << minutes.count() << "m ";
    std::cout << seconds.count() << "s ";
    std::cout << milliseconds.count() << "ms ";
    std::cout << microseconds.count() << "us ";
    std::cout << nanoseconds.count() << "ns\n";
}

It depends on your implementation what exactly the resolution you get is. VS 11 beta claims the resolution to be 100ns, although I can't say how accurate it is.

11h 51m 57s 285ms 699us 600ns
like image 136
bames53 Avatar answered Oct 24 '22 02:10

bames53


There's an article from Microsoft "Implement a Continuously Updating, High-Resolution Time Provider for Windows" detailing how to use QueryPerformanceCounter to get high resolution times.

like image 1
Mark Ransom Avatar answered Oct 24 '22 02:10

Mark Ransom