c++ - 测量时差

标签 c++ time localtime

我想以毫秒为单位测量我启动应用程序与另一时间(例如 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/

相关文章:

java - 如何使用 Joda 将服务器时间转换为本地时间?

java - 本地时间求和 (Java)

c++ - 自制bgr2hsv和opencv bgr2hsv结果不同

c++ - 为 x64 使用 msvc 编译 libssh

c - 使用 scanf 解析 hh :mm:ss, 一些输入出现奇怪的错误

perl - 确定另一个时区的本地时间

c++ - 在子语句的最外层 block 中重新声明的变量

c++ - 绘图功能的表现

c++ - 测量将参数传递给函数所需的时间

php - 如果时间和日期早于 php