MCPcopy Create free account
hub / github.com/catboost/catboost / ProcessUptime

Function ProcessUptime

util/datetime/process_uptime.cpp:16–52  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14#endif
15
16TDuration ProcessUptime() {
17#if defined(_win_)
18 FILETIME createProcessTime;
19 FILETIME dummy1;
20 FILETIME dummy2;
21 FILETIME dummy3;
22 if (GetProcessTimes(GetCurrentProcess(), &createProcessTime, &dummy1, &dummy2, &dummy3)) {
23 timeval processCreationTimeval{.tv_sec = 0, .tv_usec = 0};
24 FileTimeToTimeval(&createProcessTime, &processCreationTimeval);
25 const TInstant processCreationInstant = TInstant::Seconds(processCreationTimeval.tv_sec) + TDuration::MicroSeconds(processCreationTimeval.tv_usec);
26 return TInstant::Now() - processCreationInstant;
27 }
28 ythrow TSystemError() << "Failed to obtain process starttime";
29#elif defined(_linux_)
30 static const auto statPath = "/proc/self/stat";
31 // /proc/<pid>/stat format: #21 (0-based) item - starttime %llu - The time the process started after system boot
32 TUnbufferedFileInput statFile(statPath);
33 auto statStr = statFile.ReadAll();
34 const auto completeStatsSize = 20; // First two fields skipped to ignore variations of parentheses
35 const TVector<TStringBuf> stats = StringSplitter(TStringBuf{statStr}.RAfter(')').After(' ')).Split(' ').Take(completeStatsSize);
36 ui64 startTimeTicks = 0;
37 Y_THROW_UNLESS(stats.size() == completeStatsSize, "Broken format of " << statPath);
38 if (!TryFromString<ui64>(stats.back(), startTimeTicks)) {
39 ythrow yexception() << "Failed to extract process starttime value from " << statPath;
40 }
41 long ticksPerSecond = sysconf(_SC_CLK_TCK);
42 Y_THROW_UNLESS_EX(ticksPerSecond != -1, TSystemError() << "Failed to get _SC_CLK_TCK");
43 Y_THROW_UNLESS(ticksPerSecond > 0, "Invalid value of the _SC_CLK_TCK variable: " << ticksPerSecond);
44 const ui64 startTimeSeconds = startTimeTicks / ticksPerSecond;
45 const ui64 fractionTicks = startTimeTicks % ticksPerSecond;
46 const TDuration startTimeFractionSeconds = TDuration::MicroSeconds(1'000'000u * fractionTicks / ticksPerSecond);
47 const TDuration startTime = TDuration::Seconds(startTimeSeconds) + startTimeFractionSeconds;
48 return Uptime() - startTime;
49#else
50 ythrow yexception() << "unimplemented";
51#endif
52}

Callers 1

Y_UNIT_TESTFunction · 0.85

Calls 14

FileTimeToTimevalFunction · 0.85
MicroSecondsFunction · 0.85
StringSplitterFunction · 0.85
TSystemErrorClass · 0.85
UptimeFunction · 0.85
ReadAllMethod · 0.80
AfterMethod · 0.80
RAfterMethod · 0.80
NowFunction · 0.70
SecondsFunction · 0.50
TakeMethod · 0.45
SplitMethod · 0.45

Tested by

no test coverage detected