简体   繁体   English

如何在 C++ 中以微秒为单位获取时间戳?

[英]How to get timestamp in microseconds in C++?

I have tried this and other codes I found online but they did not work.我已经尝试过这个和我在网上找到的其他代码,但它们没有用。 My IDE is Xcode.我的 IDE 是 Xcode。 Edit: When I tried the code on the link, the variable long long microseconds always returned 0. I would like to print the timestamp in this manner: (hour:minute:microseconds).编辑:当我尝试链接上的代码时,变量 long long microseconds 总是返回 0。我想以这种方式打印时间戳:(小时:分钟:微秒)。 For example, 15:17:09:134613464312.例如,15:17:09:134613464312。

The method you use is correct.你使用的方法是正确的。

If you the code between the two now() calls lasts less than a microseconds, microseconds will always be zero, since the number is not a floating point.如果两次 now() 调用之间的代码持续时间不到一微秒,则微秒将始终为零,因为该数字不是浮点数。 If you have always zero, that means you need higher resolution (try nanoseconds).如果您始终为零,则意味着您需要更高的分辨率(尝试纳秒)。

Btw, if you simply want timestamp, you don't want to use this code since it is done to compute elapsed time between two time points.顺便说一句,如果你只是想要时间戳,你不想使用这段代码,因为它是用来计算两个时间点之间的经过时间的。 You can try something like this:你可以尝试这样的事情:

auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>
    (std::chrono::high_resolution_clock::now().time_since_epoch()).count();

Which is really a timestamp and not a duration.这实际上是一个时间戳而不是持续时间。

EDIT: To have the current microseconds count, you can do something like this:编辑:要获得当前的微秒数,您可以执行以下操作:

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

using namespace std;
using namespace std::chrono;

using days = duration<int, ratio_multiply<hours::period, ratio<24> >::type>;

int main() {
    system_clock::time_point now = system_clock::now();
    system_clock::duration tp = now.time_since_epoch();
    days d = duration_cast<days>(tp);
    tp -= d;
    hours h = duration_cast<hours>(tp);
    tp -= h;
    minutes m = duration_cast<minutes>(tp);
    tp -= m;
    seconds s = duration_cast<seconds>(tp);
    tp -= s;
    cout << tp.count() << "\n";
    return 0;
}

This will print the current microseconds count.这将打印当前的微秒计数。

Hours:Minutes:Seconds is pretty easy.小时:分钟:秒很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM