我想以毫秒为单位测量我启动应用程序与另一时间(例如 16:00 点)之间的时间间隔。执行此操作的最佳方法是什么?
我查看了“时钟”功能,但这不是我需要的。
操作系统:Win NT及以上
最佳答案
查找gettimeofday对于 POSIX 系统,和 timeGetTime适用于 Windows。
编辑:OP 似乎要求代码将当前时间/日期与另一个时间/日期进行比较。以下代码段演示了如何在 Windows 上获取当前日期和时间:
#include <Windows.h> #include <stdio.h> void main() { SYSTEMTIME st; GetSystemTime(&st); printf("Year:%d\nMonth:%d\nDate:%d\nHour:%d\nMin:%d\nSecond:%d\n" ,st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond); }
下面是计算两个 SYSTEMTIME 对象之间差异的方法:
#include <windows.h> #include <iostream> // Return time difference in units of 100 us. _int64 Delta(const SYSTEMTIME st1, const SYSTEMTIME st2) { union timeunion { FILETIME fileTime; ULARGE_INTEGER ul; } ; timeunion ft1; timeunion ft2; SystemTimeToFileTime(&st1, &ft1.fileTime); SystemTimeToFileTime(&st2, &ft2.fileTime); return ft2.ul.QuadPart - ft1.ul.QuadPart; } int main() { SYSTEMTIME t1 = {0}, t2 = {0}; t1.wDay = 10; t1.wMonth = 4; t1.wYear = 2009; t2.wDay = 12; t2.wMonth = 4; t2.wYear = 2009; _int64 i = Delta(t1, t2); std::cout << "times are " << i / 10000000 << " seconds apart\n"; return 0; }
这两个示例应该为您提供执行所需操作的工具。
关于c++ - 测量时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4445524/