【问题标题】:Linux and Windows millisecond timeLinux 和 Windows 毫秒时间
【发布时间】:2013-05-09 11:26:52
【问题描述】:

我想获得系统的毫秒时间(我不在乎它是否是实时的,我希望它尽可能准确)。这是一个好方法吗?

#ifdef WIN32
unsigned long long freq;
unsigned long long get_ms_time() {
    LARGE_INTEGER t;
    QueryPerformanceCounter(&t);
    return t.QuadPart / freq;
}
#else
unsigned long long get_ms_time() {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
#endif

如何将此值包装为带符号的 int?我试过这样做,我得到这样的负值(在 Linux 上,我不知道在 Windows 上):

~ start
-2083002438
~ 15 seconds after..
-2082987440
~ 15 seconds after..
-2082972441

我想要这样的东西。 ~ 开始 X ~ 15 秒后.. X + 14998 ~ 15 秒后.. X + 29997

其中 X 是一个正数。 (我希望输出为正并增加)

【问题讨论】:

  • 你为什么不向我们展示你的代码?
  • 您显示的代码看起来不错,所以我怀疑您打印的值错误 + 或做错了什么。
  • int x = (int) get_ms_time(); cout
  • @dan,int 通常小于 long long。无论如何,看看<chrono> 标头。
  • 我知道它更小。我正在寻找一种将 long long 包裹在 int 周围的方法。

标签: c++ time cross-platform


【解决方案1】:

我在我的代码中做了这样的事情......

timespec specStart, specStop;

// Get start time ( UNIX timestamp ) in seconds...
clock_gettime( CLOCK_MONOTONIC_RAW, &startTime );

int startTimeInt = startTime.tv_sec;
std::cout << "start time : " << startTimeInt << std::endl;

...
// Get stop time ( UNIX timestamp ) in seconds...
clock_gettime( CLOCK_MONOTONIC_RAW, &stopTime );

int stopTimeInt = stopTime.tv_sec;
std::cout << "stop time : " << stopTimeInt << std::endl;

// Get time diff from stop time to start time
unsigned long long timeStart = specStart.tv_sec * 1000000000 + specStart.tv_nsec;
unsigned long long timeStop = specStop.tv_sec * 1000000000 + specStop.tv_nsec;
unsigned long long timeDelta = timeStio - timeStart; // Time diff in nanoseconds. 

int microSec = timeDelate / 1000; 
int mSec = timeDelta / 1000000;
int sec = timeDelta / 1000000000;

std::cout << "time diff : " << std::endl
    << sec << " s" << std::endl
    << msec << " ms" << std::endl
    << microSec << " µs" << std::endl
    << timeDelta << " ns" << std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2017-04-25
    相关资源
    最近更新 更多