1 /* User/system CPU time clocks that follow the std::chrono interface. 2 Copyright (C) 2016-2025 Free Software Foundation, Inc. 3 4 This file is part of GDB. 5 6 This program is free software; you can redistribute it and/or modify 7 it under the terms of the GNU General Public License as published by 8 the Free Software Foundation; either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU General Public License for more details. 15 16 You should have received a copy of the GNU General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 18 19 #include "run-time-clock.h" 20 #if defined HAVE_SYS_RESOURCE_H 21 #include <sys/resource.h> 22 #endif 23 24 using namespace std::chrono; 25 26 run_time_clock::time_point 27 run_time_clock::now () noexcept 28 { 29 return time_point (microseconds (get_run_time ())); 30 } 31 32 #ifdef HAVE_GETRUSAGE 33 static std::chrono::microseconds 34 timeval_to_microseconds (struct timeval *tv) 35 { 36 return (seconds (tv->tv_sec) + microseconds (tv->tv_usec)); 37 } 38 #endif 39 40 /* See run-time-clock.h. */ 41 42 bool 43 get_run_time_thread_scope_available () 44 { 45 #if defined HAVE_GETRUSAGE && defined RUSAGE_THREAD 46 return true; 47 #else 48 return false; 49 #endif 50 } 51 52 void 53 get_run_time (user_cpu_time_clock::time_point &user, 54 system_cpu_time_clock::time_point &system, 55 run_time_scope scope) noexcept 56 { 57 #ifdef HAVE_GETRUSAGE 58 59 /* If we can't provide thread scope run time usage, fallback to 60 process scope. This will at least be right if GDB is built 61 without threading support in the first place (or is set to use 62 zero worker threads). */ 63 # ifndef RUSAGE_THREAD 64 # define RUSAGE_THREAD RUSAGE_SELF 65 # endif 66 67 struct rusage rusage; 68 int who; 69 70 switch (scope) 71 { 72 case run_time_scope::thread: 73 who = RUSAGE_THREAD; 74 break; 75 76 case run_time_scope::process: 77 who = RUSAGE_SELF; 78 break; 79 80 default: 81 gdb_assert_not_reached ("invalid run_time_scope value"); 82 } 83 84 getrusage (who, &rusage); 85 86 microseconds utime = timeval_to_microseconds (&rusage.ru_utime); 87 microseconds stime = timeval_to_microseconds (&rusage.ru_stime); 88 user = user_cpu_time_clock::time_point (utime); 89 system = system_cpu_time_clock::time_point (stime); 90 #else 91 user = user_cpu_time_clock::time_point (microseconds (get_run_time ())); 92 system = system_cpu_time_clock::time_point (microseconds::zero ()); 93 #endif 94 } 95