C++,从午夜开始获得毫秒数的最快方法 [英] C++, fastest way to get milliseconds since midnight

查看:33
本文介绍了C++,从午夜开始获得毫秒数的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是经常运行且必须快速运行的代码,因此我想就最快的实现方式获得一些意见.请注意,我实际上需要达到某种程度的准确度的完整毫秒分辨率(因此秒 * 1000 是不够的).对于这个项目,使用 Boost 是可以的.

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.

目标平台是 x64_86 CentOS5,也希望能够依赖操作系统时钟,所以我也可以在不连续运行的程序中使用它.

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.

推荐答案

C++ 有处理时间的 chrono 库:

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";
}

这取决于您的实施,您获得的分辨率究竟是什么.VS 11 beta 声称分辨率为 100ns,但我不能说它有多准确.

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

这篇关于C++,从午夜开始获得毫秒数的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆