Skip to content

Instantly share code, notes, and snippets.

@mooware
Created March 3, 2016 01:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mooware/b0011c88f4baf460d726 to your computer and use it in GitHub Desktop.
Save mooware/b0011c88f4baf460d726 to your computer and use it in GitHub Desktop.
Similar to the "time" or "timeit" commands, for Windows.
#include <Windows.h>
#include <Psapi.h>
#include <stdio.h>
#include <stdint.h>
uint64_t fileTimeToUsec(const FILETIME &ft)
{
return ((uint64_t(ft.dwHighDateTime) << 32) | ft.dwLowDateTime) / 10;
}
void printDuration(const wchar_t *prefix, uint64_t duration)
{
const uint64_t USEC_PER_SEC = 1000 * 1000;
uint64_t sec = duration / USEC_PER_SEC;
uint64_t usec = duration % USEC_PER_SEC;
wprintf(L"%s: %llu sec %llu usec\n", prefix, sec, usec);
}
int wmain(int argc, wchar_t **argv)
{
if (argc < 2)
{
wprintf(L"usage: %s <executable> [<args>]\n", argv[0]);
return 1;
}
wchar_t *exe = argv[1];
wchar_t *args = argv[2]; // could be null
STARTUPINFOW si = { 0 };
PROCESS_INFORMATION pi = { 0 };
si.cb = (DWORD) sizeof(si);
BOOL ok = CreateProcessW(exe, args, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (!ok)
{
wprintf(L"CreateProcess() failed, error %d\n", GetLastError());
return 1;
}
// we're not closing any handles, because we will exit soon anyway
// wait for process to end
HANDLE h = pi.hProcess;
WaitForSingleObject(h, INFINITE);
DWORD exitCode;
ok = GetExitCodeProcess(h, &exitCode);
if (!ok)
{
wprintf(L"GetExitCodeProcess() failed, error %d\n", GetLastError());
return 1;
}
FILETIME times[4];
ok = GetProcessTimes(h, &times[0], &times[1], &times[2], &times[3]);
if (!ok)
{
wprintf(L"GetProcessTimes() failed, error %d\n", GetLastError());
return 1;
}
PROCESS_MEMORY_COUNTERS mem;
ok = GetProcessMemoryInfo(h, &mem, (DWORD) sizeof(mem));
if (!ok)
{
wprintf(L"GetProcessMemoryInfo() failed, error %d\n", GetLastError());
return 1;
}
wprintf(L"\nexit code: %lu\n\n", exitCode);
printDuration(L"real time", fileTimeToUsec(times[1]) - fileTimeToUsec(times[0]));
printDuration(L"user time", fileTimeToUsec(times[3]));
printDuration(L"kernel time", fileTimeToUsec(times[2]));
wprintf(L"\n"
L"peak working set: %llu bytes\n"
L"peak page file usage: %llu bytes\n",
mem.PeakWorkingSetSize, mem.PeakPagefileUsage);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment