-
Notifications
You must be signed in to change notification settings - Fork 0
/
time_it.cpp
81 lines (77 loc) · 2.54 KB
/
time_it.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <Windows.h>
#include <string>
#include <string.h>
#include <vector>
#include <iomanip>
#include <iostream>
inline unsigned __int64 TimeToInt64(const FILETIME& file_time) {
ULARGE_INTEGER i;
i.LowPart = file_time.dwLowDateTime;
i.HighPart = file_time.dwHighDateTime;
return i.QuadPart;
}
void PrintTime(const std::string& name, unsigned __int64 time_value) {
unsigned __int64 minutes = time_value / (60 * 10000000);
time_value = time_value % (60 * 10000000);
double seconds = static_cast<double>(time_value) / 10000000.;
unsigned __int64 hours = minutes / 60;
minutes = minutes % 60;
if (hours > 0) {
std::cout << name << "\t"
<< hours << "h"
<< minutes << "m"
<< std::setprecision(3) << std::fixed << seconds << "s"
<< std::endl;
} else {
std::cout << name << "\t"
<< minutes << "m"
<< std::setprecision(3) << std::fixed << seconds << "s"
<< std::endl;
}
}
int wmain(int argc, wchar_t* argv[])
{
if (argc < 2) {
std::cout << "Usage:" << std::endl << "time_it command [arguments]" << std::endl;
std::cout << "Measures execution time of command" << std::endl;
return 1;
}
std::wstring command_buffer;
for (int i = 1; i < argc; ++i) {
if (i > 1)
command_buffer += L" ";
command_buffer += argv[i];
}
STARTUPINFOW si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
memset(&pi, 0, sizeof(pi));
const wchar_t* data = command_buffer.c_str();
std::vector<wchar_t> vt_buffer(data, data + command_buffer.length() + 1);
BOOL bOk = CreateProcessW(NULL, &vt_buffer[0],
NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (!bOk || !pi.hProcess) {
DWORD err = GetLastError();
std::wcerr << "Failed execute \"" << command_buffer;
std::wcerr << "\". GetLastError " << err << std::endl;
return 1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
FILETIME creation_time = {0, 0};
FILETIME exit_time = {0, 0};
FILETIME kernel_time = {0, 0};
FILETIME user_time = {0, 0};
if (!GetProcessTimes(pi.hProcess, &creation_time, &exit_time, &kernel_time, &user_time)) {
DWORD err = GetLastError();
std::wcerr << "GetProcessTimes failed. GetLastError " << err << std::endl;
return 1;
}
unsigned __int64 real_time = TimeToInt64(exit_time) - TimeToInt64(creation_time);
PrintTime("real", real_time);
PrintTime("user", TimeToInt64(user_time));
PrintTime("sys", TimeToInt64(kernel_time));
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}