【问题标题】:Programmatically compute the start time of a process on Windows以编程方式计算 Windows 上进程的开始时间
【发布时间】:2025-12-16 03:50:02
【问题描述】:

我正在使用 Visual Studio 在 Windows 上编写 c/c++ 代码。我想知道如何有效地计算我的流程的开始时间。我可以只使用 gettimeofday() 吗?我从谷歌找到了以下代码,但我不明白它到底在做什么:

int gettimeofday(struct timeval *tv, struct timezone *tz)
{
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag;

  if (NULL != tv)
  {
    GetSystemTimeAsFileTime(&ft);

    //I'm lost at this point
    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    /*converting file time to unix epoch*/
    tmpres /= 10;  /*convert into microseconds*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS; 
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz)
  {
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }

  return 0;
}

【问题讨论】:

  • GMan,你是如何让代码看起来不错的?我尝试使用代码标签,但它不起作用
  • 你必须在每一行前加上四个空格,而不仅仅是第一个。
  • 我认为您需要更具体地说明“计算开始时间”的含义。您是否希望能够以人类可读的形式打印出来,例如“2009 年 7 月 24 日晚上 8 点 14 分”?或者你想在计算中使用它,例如测量自上次运行程序以来经过的时间?或者是其他东西?答案取决于您想对时间值做什么。

标签: c++ windows process time


【解决方案1】:

如果我理解正确,您想知道您的流程是什么时候开始的,对吗?所以你会想看看GetProcessTimes

如果您感兴趣的进程是当前进程,您可以使用GetCurrentProcess() 获取您需要调用的进程句柄GetProcessTimes() 这将返回一个您不需要的伪句柄关闭。

【讨论】:

  • 我看到人们正在编辑 9 年前的帖子以重新格式化它们。这是一种新时尚吗?
【解决方案2】:

我的问题已结束。我从流程快照中找到了 GetProcessTime 的示例,有些人给出了这个问题的链接。

我发布了这个,这就是我的例子:

HANDLE hSnapshot; //variable for save snapshot of process
PROCESSENTRY32 Entry; //variable for processing with snapshot
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //do snapshot
Entry.dwSize = sizeof(Entry);    //assign size of Entry variables
Process32First(hSnapshot, &Entry); //assign Entry variable to start of snapshot
HANDLE hProc; //this variable for handle process
SYSTEMTIME sProcessTime; // this variable for get system (usefull) time
FILETIME fProcessTime, ftExit, ftKernel, ftUser; // this variables for get process start time and etc.
do 
{
    hProc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, Entry.th32ProcessID);//Open process for all access
    GetProcessTimes(hProc, &fProcessTime, &ftExit, &ftKernel, &ftUser);//Get process time
    FileTimeToSystemTime(&fProcessTime, &sProcessTime); //and now, start time of process at sProcessTime variable at usefull format.
} while (Process32Next(hSnapshot, &Entry)); //while not end of list(snapshot)

【讨论】:

  • 你应该关闭句柄以避免句柄泄漏,你在循环中打开句柄而不关闭它们 - 那是内核的噩梦。在 GetProcessTimes 之后使用 CloseHandle(hProc),在循环之后使用 CloseHandle(hSnapshot)