【问题标题】:How do you print a C++11 time_point?如何打印 C++11 时间点?
【发布时间】:2013-03-24 12:18:00
【问题描述】:

我已经创建了一个时间点,但我一直在努力将它打印到终端。

#include <iostream>
#include <chrono>

int main(){

    //set time_point to current time
    std::chrono::time_point<std::chrono::system_clock,std::chrono::nanoseconds> time_point;
    time_point = std::chrono::system_clock::now();

    //print the time
    //...

    return 0;
}

我能找到的唯一一个打印 time_point 的文档在这里: http://en.cppreference.com/w/cpp/chrono/time_point

但是,我什至无法根据我的 time_point(如示例)创建 time_t。

std::time_t now_c = std::chrono::system_clock::to_time_t(time_point); //does not compile

错误:

/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono: In instantiation of ‘constexpr std::chrono::time_point<_Clock, _Dur>::time_point(const std::chrono::time_point<_Clock, _Dur2>&) [with _Dur2 = std::chrono::duration<long int, std::ratio<1l, 1000000000l> >; _Clock = std::chrono::system_clock; _Dur = std::chrono::duration<long int, std::ratio<1l, 1000000l> >]’:
time.cpp:13:69:   required from here
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:540:32: error: no matching function for call to ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >::duration(std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >::duration)’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:540:32: note: candidates are:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:247:14: note: template<class _Rep2, class _Period2, class> constexpr std::chrono::duration::duration(const std::chrono::duration<_Rep2, _Period2>&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:247:14: note:   template argument deduction/substitution failed:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:243:46: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:240:23: note: template<class _Rep2, class> constexpr std::chrono::duration::duration(const _Rep2&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:240:23: note:   template argument deduction/substitution failed:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:236:27: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:234:12: note: constexpr std::chrono::duration<_Rep, _Period>::duration(const std::chrono::duration<_Rep, _Period>&) [with _Rep = long int; _Period = std::ratio<1l, 1000000l>]
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:234:12: note:   no known conversion for argument 1 from ‘std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >::duration {aka std::chrono::duration<long int, std::ratio<1l, 1000000000l> >}’ to ‘const std::chrono::duration<long int, std::ratio<1l, 1000000l> >&’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:232:12: note: constexpr std::chrono::duration<_Rep, _Period>::duration() [with _Rep = long int; _Period = std::ratio<1l, 1000000l>]
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:232:12: note:   candidate expects 0 arguments, 1 provided

【问题讨论】:

  • 我相信libstdc++(即STL的GCC实现)还不支持std::put_time,然后cppreference中的示例无法编译。见gcc.gnu.org/onlinedocs/libstdc++/manual/status.html
  • 顺便说一句,如果您单击“运行此代码”,然后将编译器更改为clang 3.4 (C++11),cppreference 上的示例将编译

标签: c++ templates time c++11 chrono


【解决方案1】:

(在这篇文章中,为了清楚起见,我将省略 std::chrono:: 限定条件。我相信你知道它们的去向。)

您的代码示例无法编译的原因是 system_clock::now() 的返回类型与您尝试将其分配给的变量类型 (time_point&lt;system_clock, nanoseconds&gt;) 不匹配。

system_clock::now() 的记录返回值为system_clock::time_point,它是time_point&lt;system_clock, system_clock::duration&gt; 的类型定义。 system_clock::duration 是实现定义的,microseconds 和 nanoseconds 是常用的。看来你的实现使用了microseconds,所以system_clock::now()的返回类型是time_point&lt;system_clock, microseconds&gt;。

具有不同持续时间的time_points 不能隐式相互转换,因此会出现编译器错误。

您可以显式使用time_point_cast 转换具有不同持续时间的时间点,因此以下代码将在您的系统上编译:

time_point<system_clock, nanoseconds> time_point;
time_point = time_point_cast<nanoseconds>(system_clock::now());

注意time_point_cast 的显式模板参数是目标duration 类型,而不是目标time_point 类型。时钟类型必须在 time_point_cast 中匹配,因此指定整个 time_point 类型(在时钟类型和持续时间类型上都被模板化)将是多余的。

当然,在您的情况下,由于您只是想打印时间点,因此不需要任何特定的分辨率,因此您可以将 time_point 声明为与 @987654339 相同的类型@ 返回开头。一个简单的方法是使用system_clock::time_point typedef:

system_clock::time_point time_point;
time_point = system_clock::now();  // no time_point_cast needed

由于这是C++11,你也可以直接使用auto:

auto time_point = system_clock::now(); 

解决了这个编译器错误后,转换为time_t 就可以了:

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

您现在可以使用标准方法来显示time_t 值,例如std::ctime 或std::strftime。 (正如 Cassio Neri 在对您问题的评论中指出的那样,GCC 尚不支持更多 C++-y std::put_time 函数)。

【讨论】:

  • +1 要获得更全面的解释并提及auto(实际上,它是C++,没有人声明变量并在下一行分配它,即使没有auto)。跨度>
  • @HighCommander4: time_point 具有不同的持续时间 可以隐式转换为彼此 如果 它们共享相同的 Clock 并且如果rhs Duration 可隐式转换为 lhs Duration。在此示例中,如果 system_clock::duration 是微秒或纳秒,它确实根据 [time.point.cons]/p3 隐式转换为 time_point&lt;system_clock, nanoseconds&gt;。
【解决方案2】:

旧问题的更新答案:

对于std::chrono::time_point&lt;std::chrono::system_clock, some-duration&gt;,现在有一个第三方库可以让您更好地控制。对于基于其他时钟的time_points,仍然没有比只获取内部表示并打印出来更好的解决方案。

但是对于system_clock,使用this library,这很简单:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << system_clock::now() << " UTC\n";
}

这只是为我输出:

2016-07-19 03:21:01.910626 UTC

这是当前 UTC 日期和时间,精度为微秒。如果在您的平台上system_clock::time_point 具有纳秒精度,它将为您打印出纳秒精度。

2021 年更新

这是上述程序的C++20版本:

#include <chrono>
#include <iostream>

int
main()
{
    std::cout << std::chrono::system_clock::now() << " UTC\n";
}

【讨论】:

  • 嗯,这应该在标准 imo 中。
  • @AbhinavGauniyal:正在研究它 (open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0355r1.html)。这很可能需要您的非常明确的帮助。委员会中的重要力量不喜欢这个提议,如果公众不大声疾呼,他们就会获胜。
  • 具有替代(恕我直言)设计的竞争提案。寻找我的提案的修订版 3,以便在大约一周内出现在 open-std.org/jtc1/sc22/wg21/docs/papers/2017
  • 现在 date.h 的“略微修改版本”进入了 C++ 2a,time_point 输出是它的一部分吗?我正在使用带有 -std=c++2a 的最新 gcc,但没有得到它
  • time_point output when time_point is based on system_clock 是 C++2a 草案的一部分。虽然这是一个很大的提议,但据我所知,还没有人发货。
【解决方案3】:

这个 sn-p 可能会对你有所帮助:

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

template<typename Clock, typename Duration>
std::ostream &operator<<(std::ostream &stream,
  const std::chrono::time_point<Clock, Duration> &time_point) {
  const time_t time = Clock::to_time_t(time_point);
#if __GNUC__ > 4 || \
    ((__GNUC__ == 4) && __GNUC_MINOR__ > 8 && __GNUC_REVISION__ > 1)
  // Maybe the put_time will be implemented later?
  struct tm tm;
  localtime_r(&time, &tm);
  return stream << std::put_time(&tm, "%c"); // Print standard date&time
#else
  char buffer[26];
  ctime_r(&time, buffer);
  buffer[24] = '\0';  // Removes the newline that is added
  return stream << buffer;
#endif
}

int main() {
  std::cout << std::chrono::system_clock::now() << std::endl;
  // Wed May 22 14:17:03 2013
}

【讨论】:

  • 只有std::chrono::system_clock 支持to_time_t 所以我认为把它作为模板是没有意义的。相反,time_point 可以直接作为const system_clock::time_point &amp;time_point 传递。
  • 取决于用户是否创建了带有to_time_t 的用户定义时钟。
【解决方案4】:

nanoseconds 似乎是问题的一部分,稍微查看一下文档我就能让它工作:

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


int main(){

    //set time_point to current time
    std::chrono::time_point<std::chrono::system_clock> time_point;
    time_point = std::chrono::system_clock::now();

    std::time_t ttp = std::chrono::system_clock::to_time_t(time_point);
    std::cout << "time: " << std::ctime(&ttp);

    return 0;
}

虽然看起来std::chrono::microseconds 工作正常:

std::chrono::time_point<std::chrono::system_clock,std::chrono::microseconds> time_point;

【讨论】:

  • 顺便说一句,更简洁的auto time_point = std::chrono::system_clock::now(); 也可以做到。
  • @ChristianRau 当然,公平点,我通常希望代码尽可能接近原始发布的代码,除非它明显损坏或错误。
  • 还有一个更简洁的:high_resolution_clock::now().
【解决方案5】:

对于使用time_point&lt;steady_clock&gt;(不是time_point&lt;system_clock&gt;)的任何人:

#include <chrono>
#include <iostream>

template<std::intmax_t resolution>
std::ostream &operator<<(
    std::ostream &stream,
    const std::chrono::duration<
        std::intmax_t,
        std::ratio<std::intmax_t(1), resolution>
    > &duration)
{
    const std::intmax_t ticks = duration.count();
    stream << (ticks / resolution) << '.';
    std::intmax_t div = resolution;
    std::intmax_t frac = ticks;
    for (;;) {
        frac %= div;
        if (frac == 0) break;
        div /= 10;
        stream << frac / div;
    }
    return stream;
}

template<typename Clock, typename Duration>
std::ostream &operator<<(
    std::ostream &stream,
    const std::chrono::time_point<Clock, Duration> &timepoint)
{
    Duration ago = timepoint.time_since_epoch();
    return stream << ago;
}

int main(){
    // print time_point
    std::chrono::time_point<std::chrono::steady_clock> now =
        std::chrono::steady_clock::now();
    std::cout << now << "\n";

    // print duration (such as the difference between 2 time_points)
    std::chrono::steady_clock::duration age = now - now;
    std::cout << age << "\n";
}

十进制数格式化器不是最有效的,但不需要预先知道小数位数,如果您希望 resolution 被模板化,则不知道,除非您可以为 @987654326 提供一个常量表达式@。

【讨论】:

  • 为了获得额外的速度,你可以使用我的 itoa(它确实有一个 ceil(log10(resolution) 的常量表达式,但只是静态断言传递的缓冲区足够大;)...@987654321 @
【解决方案6】:

ctime() 不适用于 Visual C++。我使用 MS Visual Studio 2013。根据 MSVC 编译器的提示,我将上述代码更改为使用 ctime_s(...)。它奏效了。

//set time_point to current time
std::chrono::time_point<std::chrono::system_clock> time_point;
time_point = std::chrono::system_clock::now();

std::time_t ttp = std::chrono::system_clock::to_time_t(time_point);
char chr[50];
errno_t e = ctime_s(chr, 50, &ttp);
if (e) std::cout << "Error." << std::endl;
else std::cout << chr << std::endl;

【讨论】:

    【解决方案7】:

    又一个 sn-p 代码。 优点是它相当独立并且支持微秒文本表示。

    std::ostream& operator<<(std::ostream& stream, const std::chrono::system_clock::time_point& point)
    {
        auto time = std::chrono::system_clock::to_time_t(point);
        std::tm* tm = std::localtime(&time);
        char buffer[26];
        std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S.", tm);
        stream << buffer;
        auto duration = point.time_since_epoch();
        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
        auto remaining = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - seconds);
        // remove microsecond cast line if you would like a higher resolution sub second time representation, then just stream remaining.count()
        auto micro = std::chrono::duration_cast<std::chrono::microseconds>(remaining);
        return stream << micro.count();
    }
    

    【讨论】:

      【解决方案8】:

      tl;dr 如何打印原始std::chrono::time_point

      #include <iostream>
      #include <chrono>
      
      int main()
      {
        // begin is a std::chrono::time_point type
        // You can also use ::system_clock::now() to get the time since
        // Jan 1 1970 (differences between these linked below)
        auto begin = std::chrono::steady_clock::now();
      
        // print as nanoseconds. Can also choose ::microseconds, ::seconds, ::minutes,
        // ::hours. The type returned from .time_since_epoch() is
        // std::chrono::duration
        std::cout << "begin: " << std::chrono::duration_cast<std::chrono::nanoseconds>(begin.time_since_epoch()).count();
      
        return 0;
      }
      

      天哪,我认为 30 秒的谷歌搜索变成了一个研究项目。我想做的只是在我的程序中打印出一些原始时间点来直观地比较它们,对漂亮的打印不感兴趣。我确信这些其他答案也有效,但是它们有很多代码,使用 ctime structs、3rd 方库等。我正在寻找一个最小的、“按原样打印这个值”的解决方案,但没有找不到那么多直接的。看来你不能简单地打印一个::time_point:

      auto begin = std::chrono::steady_clock::now();
      // BAD CODE, none of these work, in C++17 anyway
      std::cout << begin;
      std::cout << std::chrono::time_point_cast<std::chrono::nanoseconds>(begin);
      std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(begin).count();
      std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(begin - 0).count();
      

      相反,您似乎只能打印持续时间,因此顶部说明的是创建持续时间的快速方法(来自here),从now 直到开始纪元,这取决于您使用的时钟(基本上,::system_clock 是挂钟时间,::steady_clock 是从某个时间点开始的单调时钟,例如系统开机)。就我的目的而言,::steady_clock 肯定是更好的选择,但只要我将苹果与苹果进行比较,这并不重要。我只是在寻找一些视觉反馈,而不是超级准确的。

      我在这里创建了一个暂存器demonstration,说明如何打印我感兴趣的时间点,以及::steady_clock 和::system_clock 之间的一些差异。

      【讨论】:

        猜你喜欢
        • 2014-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多