7

我尝试了几种方法来打印时间,system_clock但除了整秒之外我什么也得不到:

system_clock::time_point now = system_clock::now();
std::time_t now_c = system_clock::to_time_t(now);

std::cout<<ctime(&now_c);
std::cout<<std::put_time(std::localtime(&now_c), "%T")<<" ";

now()函数是否实际上保存了高精度数据,或者我只是找不到提取该信息进行打印的函数?

注意:我不想计算时间间隔。我想要几分之一秒的当前时间cout,并通过. 我只是找不到办法做到这一点。

而且我知道std::chrono::high_resolution_clock但也没有办法打印出它的now(). 此外,该setprecision函数对put_timeor的输出没有影响ctime

我得到的答案实际上并没有解决这个问题。

4

3 回答 3

9

您可以执行以下操作:

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

std::string GetLocalTime() {
  auto now(std::chrono::system_clock::now());
  auto seconds_since_epoch(
      std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()));

  // Construct time_t using 'seconds_since_epoch' rather than 'now' since it is
  // implementation-defined whether the value is rounded or truncated.
  std::time_t now_t(
      std::chrono::system_clock::to_time_t(
          std::chrono::system_clock::time_point(seconds_since_epoch)));

  char temp[10];
  if (!std::strftime(temp, 10, "%H:%M:%S.", std::localtime(&now_t)))
    return "";

  return std::string(temp) +
      std::to_string((now.time_since_epoch() - seconds_since_epoch).count());
}

int main() {
  std::cout << GetLocalTime() << '\n';
  return 0;
}
于 2013-04-06T02:04:53.227 回答
2

现有答案很好,但它错过了秒的小数部分的前导零,因此 21:10:30.01 将返回为 21:10:30.1

我没有代表发表评论,我的编辑被拒绝,所以这是一个固定版本:

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

std::string GetLocalTime() {
  auto now(std::chrono::system_clock::now());
  auto seconds_since_epoch(
    std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()));

  // Construct time_t using 'seconds_since_epoch' rather than 'now' since it is
  // implementation-defined whether the value is rounded or truncated.
  std::time_t now_t(
    std::chrono::system_clock::to_time_t(
      std::chrono::system_clock::time_point(seconds_since_epoch)));

  char temp[10];
  if (!std::strftime(temp, 10, "%H:%M:%S.", std::localtime(&now_t)))
    return "";

  std::string nanoseconds = std::to_string(
    (std::chrono::duration<long long, std::nano>(
      now.time_since_epoch() - seconds_since_epoch)).count());

  return std::string(temp) + std::string(9-nanoseconds.length(),'0') + nanoseconds;
}

int main() {
  std::cout << GetLocalTime() << '\n';
  return 0;
}
于 2019-03-03T21:30:07.323 回答
-2

尝试std::chrono::high_resolution_clock。(我认为它只有 c++11)

于 2013-04-06T00:23:50.150 回答