OpenVPN 3 Core Library
Loading...
Searching...
No Matches
cputime.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#pragma once
13
14#include <errno.h>
15#include <sys/time.h>
16#include <sys/types.h>
17#include <sys/resource.h>
18#include <unistd.h>
19
20#include <string>
21
26
27#if defined(__APPLE__)
28#include <mach/mach.h>
29
34static int getrusage_thread(struct rusage &rusage)
35{
36 int ret = -1;
37 thread_basic_info_data_t info{};
38 mach_msg_type_number_t info_count = THREAD_BASIC_INFO_COUNT;
39 kern_return_t kern_err;
40
41 kern_err = thread_info(mach_thread_self(),
42 THREAD_BASIC_INFO,
43 (thread_info_t)&info,
44 &info_count);
45 if (kern_err == KERN_SUCCESS)
46 {
47 rusage.ru_utime.tv_sec = info.user_time.seconds;
48 rusage.ru_utime.tv_usec = info.user_time.microseconds;
49 rusage.ru_stime.tv_sec = info.system_time.seconds;
50 rusage.ru_stime.tv_usec = info.system_time.microseconds;
51 ret = 0;
52 }
53 else
54 {
55 errno = EINVAL;
56 }
57 return ret;
58}
59
60#endif
61
62namespace openvpn {
76inline double cpu_time(const bool thread = false)
77{
78 try
79 {
80 struct rusage usage
81 {
82 };
83
84 int ret = 0;
85#if defined(__APPLE__)
86 if (thread)
87 ret = getrusage_thread(usage);
88 else
89 ret = getrusage(RUSAGE_SELF, &usage);
90#else
91 ret = getrusage((thread ? RUSAGE_THREAD : RUSAGE_SELF), &usage);
92#endif
93 if (ret != 0)
94 {
95 throw Exception("getrusage() call failed: " + std::string(strerror(errno)));
96 }
97 double utime = static_cast<double>(usage.ru_utime.tv_sec) + (static_cast<double>(usage.ru_utime.tv_usec / 1000000));
98 double stime = static_cast<double>(usage.ru_stime.tv_sec) + (static_cast<double>(usage.ru_stime.tv_usec / 1000000));
99
100 return utime + stime;
101 }
102 catch (const std::exception &e)
103 {
104 // OPENVPN_LOG("cpu_time exception: " << e.what());
105 return -1.0;
106 }
107}
108
109
110} // namespace openvpn
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
double cpu_time(const bool thread=false)
Definition cputime.hpp:76
std::string ret