如何在C++中获得微秒的时间戳?

rta7y2nd  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(279)

我试过this和我在网上找到的其他代码,但都不起作用。我的IDE是Xcode。编辑:当我尝试链接上的代码时,变量long long微秒总是返回0。我想以这种方式打印时间戳:(小时:分钟:微秒)。例如,15:17:09:134613464312。

h9a6wy2h

h9a6wy2h1#

你使用的方法是正确的。
如果两次now()调用之间的代码持续时间小于1微秒,则微秒将始终为零,因为该数字不是浮点数。如果总是0,这意味着你需要更高的分辨率(尝试纳秒)。
顺便说一句,如果你只是想要时间戳,你不想使用这段代码,因为它是用来计算两个时间点之间的时间。你可以试试这样的方法:

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

它实际上是一个时间戳而不是持续时间。
编辑:要获得当前的微秒计数,您可以这样做:

  1. #include <iostream>
  2. #include <chrono>
  3. #include <ctime>
  4. using namespace std;
  5. using namespace std::chrono;
  6. using days = duration<int, ratio_multiply<hours::period, ratio<24> >::type>;
  7. int main() {
  8. system_clock::time_point now = system_clock::now();
  9. system_clock::duration tp = now.time_since_epoch();
  10. days d = duration_cast<days>(tp);
  11. tp -= d;
  12. hours h = duration_cast<hours>(tp);
  13. tp -= h;
  14. minutes m = duration_cast<minutes>(tp);
  15. tp -= m;
  16. seconds s = duration_cast<seconds>(tp);
  17. tp -= s;
  18. cout << tp.count() << "\n";
  19. return 0;
  20. }

这将打印当前的微秒计数。
小时:分钟:秒是很容易的。

展开查看全部
yrefmtwq

yrefmtwq2#

在前面的答案的基础上,下面是OP的问题:

  1. #include <iostream>
  2. #include <chrono>
  3. #include <ctime>
  4. std::string ts() {
  5. using namespace std;
  6. using namespace std::chrono;
  7. using days = duration<int, ratio_multiply<hours::period, ratio<24> >::type>;
  8. high_resolution_clock::time_point now = high_resolution_clock::now();
  9. high_resolution_clock::duration tp = now.time_since_epoch();
  10. days d = duration_cast<days>(tp);
  11. tp -= d;
  12. hours h = duration_cast<hours>(tp);
  13. tp -= h;
  14. minutes m = duration_cast<minutes>(tp);
  15. tp -= m;
  16. seconds s = duration_cast<seconds>(tp);
  17. tp -= s;
  18. milliseconds ms = duration_cast<milliseconds>(tp);
  19. tp -= ms;
  20. microseconds us = duration_cast<microseconds>(tp);
  21. tp -= us;
  22. nanoseconds ns = duration_cast<nanoseconds>(tp);
  23. tp -= ns;
  24. std::ostringstream oss;
  25. oss << std::setfill('0')
  26. << std::setw(2) << h.count() << ":"
  27. << std::setw(2) << m.count() << ":"
  28. << std::setw(2) << s.count() << "."
  29. << std::setw(3) << ms.count()
  30. << std::setw(3) << us.count()
  31. << std::setw(3) << ns.count();
  32. return oss.str();
  33. }
  34. void main ()
  35. {
  36. std::cout << ts() << std::endl;
  37. std::cout << ts() << std::endl;
  38. }
  39. //output:
  40. //22:43:00.295605757
  41. //22:43:00.295640327
展开查看全部

相关问题