使用函数:
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的转换。