私が使用しているウィンドウで、エポックからの秒数を取得するためのクロスプラットフォーム ソリューションはありますか
long long NativesGetTimeInSeconds()
{
return time (NULL);
}
しかし、どうやって Linux に乗るのでしょうか?
あなたはすでにそれを使用しています: std::time(0)(することを忘れないでください#include <ctime>)。ただし、std::timeエポックからの時間を実際に返すかどうかは、標準で指定されていません ( C11、C++ 標準で参照されます)。
7.27.2.4
time関数あらすじ
#include <time.h> time_t time(time_t *timer);説明
time 関数は、現在のカレンダー時間を決定します。 値のエンコーディングは指定されていません。[鉱山を強調]
C++ の場合、C++11 以降ではtime_since_epoch. ただし、C++20 より前のエポックstd::chrono::system_clockは指定されていなかったため、以前の標準ではおそらく移植できませんでした。
それでも、Linux ではstd::chrono::system_clock通常、C++11、C++14、および C++17 でも Unix Time を使用するため、次のコードを使用できます。
#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();
}
Cで。
time(NULL);
C++ で。
std::time(0);
time の戻り値は次のとおりです。
時間を取得するための Linux のネイティブ関数はgettimeofday()[他にもいくつかあります] ですが、これは必要以上の秒単位とナノ秒単位の時間を取得するため、引き続きtime(). [もちろん、どこかtime()で呼び出すことによって実装されgettimeofday()ますが、まったく同じことを行う 2 つの異なるコードを使用する利点はわかりません。それが必要な場合は、GetSystemTime()またはそのようなものを使用しますWindows [正しい名前かどうかわかりません。Windows でプログラミングを始めてからしばらく経ちます]
シンプルでポータブル、かつ適切なアプローチ
#include <ctime>
long CurrentTimeInSeconds()
{
return (long)std::time(0); //Returns UTC in Seconds
}