获取本地时间(以纳秒为单位) [英] Get local time in nanoseconds

查看:189
本文介绍了获取本地时间(以纳秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C ++计时器功能可提供以纳秒为单位的时间

Possible Duplicate:
C++ Timer function to provide time in nano seconds

我需要以纳秒分辨率来衡量函数执行的持续时间.是否有可能?我们普通的计算机硬件和软件能给时间这么精确吗?如果是,如何用c ++做到这一点? Boost库有可能吗?

I need to measure the duration of a function execution in nanoseconds resolution. Is it possible? Our ordinary computer hardware and software are able to give such a precision for time? If yes how to accomplish that with c++? Is it possible with Boost library?

推荐答案

是的,当今大多数硬件都支持这种分辨率,并且C ++标准库具有也可以支持该分辨率的API.不幸的是,并非所有的C ++实现都确实提供了它.

Yes, today most hardware supports this sort of resolution, and the C++ standard library has an API that can support it as well. Unfortunately not all implementations of C++ actually do provide it.

API是C ++ 11中引入的 <chrono> 库:/p>

The API is the <chrono> library introduced in C++11:

#include <iostream>
#include <chrono>

int main() {
    auto start = std::chrono::high_resolution_clock::now();

    // operation to be timed ...

    auto finish = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << "ns\n";
}

libc ++中针对Darwin的<chrono>实现提供了纳秒级的分辨率,但是VS2012中的实现似乎只有十分之一毫秒.上面的代码仍然会给出以纳秒为单位的时间,但是少于100微秒的时间最终将为零纳秒.

The <chrono> implementation in libc++ for Darwin provides nanosecond resolution, but it seems the implementation in VS2012 only goes to tenths of milliseconds. The above code will still give times in terms of nanoseconds, but timings less than 100 microseconds will end up being zero nanoseconds.

Boost还提供了一个实现boost :: chrono,在Windows上似乎确实使用了纳秒级.在C ++ 03中也可以使用.

Boost also provides an implemenation, boost::chrono, which does seem to use nanoseconds on Windows. It's also usable with C++03.

#include <boost/chrono.hpp>

int main() {
    boost::chrono::high_resolution_clock::time_point t1 =
        boost::chrono::high_resolution_clock::now();

    boost::chrono::high_resolution_clock::time_point t2 =
        boost::chrono::high_resolution_clock::now();

    std::cout << boost::chrono::duration_cast<boost::chrono::nanoseconds>(t2-t1) << "\n";
    // boost chrono has more advanced output, .count() isn't needed, nor is manually writing out the units
}

这篇关于获取本地时间(以纳秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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