window 获取进程运行长

使用函数:
GetCurrentProcess、OpenProcess、GetProcessTimes、FileTimeToLocalFileTime、FileTimeToSystemTime、GetLocalTime、

//SYSTEMTIME 转 时间戳 精确到 毫秒
__int64 SystemTimeToTimeT(LPSYSTEMTIME lp_system_time) {
  tm local_tm;
  SYSTEMTIME& system_times = *lp_system_time;

  local_tm.tm_year = system_times.wYear - 1900;
  local_tm.tm_mon = system_times.wMonth - 1;
  local_tm.tm_mday = system_times.wDay;
  local_tm.tm_hour = system_times.wHour;
  local_tm.tm_min = system_times.wMinute;
  local_tm.tm_sec = system_times.wSecond;
  local_tm.tm_yday = 0;
  local_tm.tm_isdst = 0;

  time_t time_stamp = mktime(&local_tm);  //秒
  time_stamp = time_stamp * 1000;
  time_stamp += system_times.wMilliseconds;  //毫秒

  return time_stamp;
}
//获取进程运行时长
__int64 GetProcessRunTimes(DWORD process_id) {
  HANDLE handle = NULL;
  if (process_id == 0) {
    handle = GetCurrentProcess();
  } else {
    handle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process_id);
  }
  if (handle == NULL) {
    return -1;
  }

  FILETIME create_times, exit_times, kernel_times, user_times;
  //创建时间时 1601/1/1 0:0:0 到现在得时间量  单位时100纳秒
  if (!GetProcessTimes(handle, &create_times, &exit_times, &kernel_times,
                       &user_times)) {
    return -1;
  }
  
  ULARGE_INTEGER large_inter;
  large_inter.LowPart = create_times.dwLowDateTime;
  large_inter.HighPart = create_times.dwHighDateTime;
  //large_inter = *(ULARGE_INTEGER*)&create_times;
  //注意越界问题
  /*UINT64 times =
      ((UINT64)create_times.dwHighDateTime << 32) + create_times.dwLowDateTime;*/
  //ULARGE_INTEGER 
  转换成真正得时间,因为不知道 0-1601年过了多久,所以用FileTimetoSystemTime 转换
  FILETIME local_file_time;
  FileTimeToLocalFileTime(&create_times, &local_file_time);
  SYSTEMTIME local_system_time;
  FileTimeToSystemTime(&local_file_time, &local_system_time);
  
  SYSTEMTIME cur_local_system_time;
  GetLocalTime(&cur_local_system_time);
  __int64 cur_time_t  = SystemTimeToTimeT(&cur_local_system_time);
  return cur_time_t - SystemTimeToTimeT(&local_system_time);
  /*return SystemTimeToTimeT(&cur_local_system_time) -
         SystemTimeToTimeT(&local_system_time);*/
}

先利用GetProcessTimes 获取到进程创建的时间,然后再利用GetLocalTime获取到当前时间,然后计算差值。过程中利用了 FILETIME 到 SYSTEMTIME的转换,SYSTEMTIME到tm的转换,tm到time_t的转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值