在Linux中获得自纪元以来的秒数

Bor*_*ris 10 c++ linux windows time

对于我使用的Windows,是否有跨平台解决方案来获得自纪元以来的秒数

long long NativesGetTimeInSeconds()
{
    return time (NULL);
}
Run Code Online (Sandbox Code Playgroud)

但是如何上Linux呢?

Zet*_*eta 20

你已经在使用它了:( std::time(0)别忘了#include <ctime>).但是,是否std::time实际返回标准中未指定epoch的时间(C11,由C++标准引用):

7.27.2.4 time功能

概要

#include <time.h>
time_t time(time_t *timer);
Run Code Online (Sandbox Code Playgroud)

描述

时间函数确定当前日历时间. 未指定值的编码.[强调我的]

C++ 11提供time_since_epoch,但epoch取决于使用的时钟.不过,你可以获得秒数:

#include <chrono>

// make the decltype slightly easier to the eye
using seconds_t = std::chrono::seconds;

// return the same type as seconds.count() below does.
// note: C++14 makes this a lot easier.
decltype(seconds_t().count()) get_seconds_since_epoch()
{
    // get the current time
    const auto now     = std::chrono::system_clock::now();

    // transform the time into a duration since the epoch
    const auto epoch   = now.time_since_epoch();

    // cast the duration into seconds
    const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(epoch);

    // return the number of seconds
    return seconds.count();
}
Run Code Online (Sandbox Code Playgroud)


Que*_*rez 14

在C.

time(NULL);
Run Code Online (Sandbox Code Playgroud)

在C++中.

std::time(0);
Run Code Online (Sandbox Code Playgroud)

并且时间的返回值是:time_t