Amir Afghani
Amir Afghani

Reputation: 38531

Programmatically compute the start time of a process on Windows

I'm writing c/c++ code on Windows using Visual Studio. I want to know how to calculate the start time of my process effectively. Can I just use gettimeofday()? I've found the following code from google but I don't understand what it's doing really :

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;
}

Upvotes: 3

Views: 8842

Answers (2)

Curt Nichols
Curt Nichols

Reputation: 2767

If I understand you right you want to know what time your process started, correct? So you'll want to look into GetProcessTimes

If the process you're interested in is the current process, you can use GetCurrentProcess() to get the process handle that you'll need to call GetProcessTimes() this returns a pseudo-handle that you don't need to close.

Upvotes: 8

Alexey1993
Alexey1993

Reputation: 105

My question is closed. I'm find example to GetProcessTime from process shapshot and some guys give link with this question.

I'm released this and that is my example:

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)

Upvotes: 4

Related Questions