You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

418 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2010 Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/base/cpumonitor.h"
  28. #include <string>
  29. #include "talk/base/common.h"
  30. #include "talk/base/logging.h"
  31. #include "talk/base/scoped_ptr.h"
  32. #include "talk/base/systeminfo.h"
  33. #include "talk/base/thread.h"
  34. #include "talk/base/timeutils.h"
  35. #ifdef WIN32
  36. #include "talk/base/win32.h"
  37. #include <winternl.h>
  38. #endif
  39. #ifdef POSIX
  40. #include <sys/time.h>
  41. #endif
  42. #if defined(IOS) || defined(OSX)
  43. #include <mach/mach_host.h>
  44. #include <mach/mach_init.h>
  45. #include <mach/host_info.h>
  46. #include <mach/task.h>
  47. #endif // defined(IOS) || defined(OSX)
  48. #if defined(LINUX) || defined(ANDROID)
  49. #include <sys/resource.h>
  50. #include <errno.h>
  51. #include <stdio.h>
  52. #include "talk/base/fileutils.h"
  53. #include "talk/base/pathutils.h"
  54. #endif // defined(LINUX) || defined(ANDROID)
  55. #if defined(IOS) || defined(OSX)
  56. static uint64 TimeValueTToInt64(const time_value_t &time_value) {
  57. return talk_base::kNumMicrosecsPerSec * time_value.seconds +
  58. time_value.microseconds;
  59. }
  60. #endif // defined(IOS) || defined(OSX)
  61. // How CpuSampler works
  62. // When threads switch, the time they spent is accumulated to system counters.
  63. // The time can be treated as user, kernel or idle.
  64. // user time is applications.
  65. // kernel time is the OS, including the thread switching code itself.
  66. // typically kernel time indicates IO.
  67. // idle time is a process that wastes time when nothing is ready to run.
  68. //
  69. // User time is broken down by process (application). One of the applications
  70. // is the current process. When you add up all application times, this is
  71. // system time. If only your application is running, system time should be the
  72. // same as process time.
  73. //
  74. // All cores contribute to these accumulators. A dual core process is able to
  75. // process twice as many cycles as a single core. The actual code efficiency
  76. // may be worse, due to contention, but the available cycles is exactly twice
  77. // as many, and the cpu load will reflect the efficiency. Hyperthreads behave
  78. // the same way. The load will reflect 200%, but the actual amount of work
  79. // completed will be much less than a true dual core.
  80. //
  81. // Total available performance is the sum of all accumulators.
  82. // If you tracked this for 1 second, it would essentially give you the clock
  83. // rate - number of cycles per second.
  84. // Speed step / Turbo Boost is not considered, so infact more processing time
  85. // may be available.
  86. namespace talk_base {
  87. // Note Tests on Windows show 600 ms is minimum stable interval for Windows 7.
  88. static const int32 kDefaultInterval = 950; // Slightly under 1 second.
  89. CpuSampler::CpuSampler()
  90. : min_load_interval_(kDefaultInterval)
  91. #ifdef WIN32
  92. , get_system_times_(NULL),
  93. nt_query_system_information_(NULL),
  94. force_fallback_(false)
  95. #endif
  96. {
  97. }
  98. CpuSampler::~CpuSampler() {
  99. }
  100. // Set minimum interval in ms between computing new load values. Default 950.
  101. void CpuSampler::set_load_interval(int min_load_interval) {
  102. min_load_interval_ = min_load_interval;
  103. }
  104. bool CpuSampler::Init() {
  105. sysinfo_.reset(new SystemInfo);
  106. cpus_ = sysinfo_->GetMaxCpus();
  107. if (cpus_ == 0) {
  108. return false;
  109. }
  110. #ifdef WIN32
  111. // Note that GetSystemTimes is available in Windows XP SP1 or later.
  112. // http://msdn.microsoft.com/en-us/library/ms724400.aspx
  113. // NtQuerySystemInformation is used as a fallback.
  114. if (!force_fallback_) {
  115. get_system_times_ = GetProcAddress(GetModuleHandle(L"kernel32.dll"),
  116. "GetSystemTimes");
  117. }
  118. nt_query_system_information_ = GetProcAddress(GetModuleHandle(L"ntdll.dll"),
  119. "NtQuerySystemInformation");
  120. if ((get_system_times_ == NULL) && (nt_query_system_information_ == NULL)) {
  121. return false;
  122. }
  123. #endif
  124. #if defined(LINUX) || defined(ANDROID)
  125. Pathname sname("/proc/stat");
  126. sfile_.reset(Filesystem::OpenFile(sname, "rb"));
  127. if (!sfile_) {
  128. LOG_ERR(LS_ERROR) << "open proc/stat failed:";
  129. return false;
  130. }
  131. if (!sfile_->DisableBuffering()) {
  132. LOG_ERR(LS_ERROR) << "could not disable buffering for proc/stat";
  133. return false;
  134. }
  135. #endif // defined(LINUX) || defined(ANDROID)
  136. GetProcessLoad(); // Initialize values.
  137. GetSystemLoad();
  138. // Help next user call return valid data by recomputing load.
  139. process_.prev_load_time_ = 0u;
  140. system_.prev_load_time_ = 0u;
  141. return true;
  142. }
  143. float CpuSampler::UpdateCpuLoad(uint64 current_total_times,
  144. uint64 current_cpu_times,
  145. uint64 *prev_total_times,
  146. uint64 *prev_cpu_times) {
  147. float result = 0.f;
  148. if (current_total_times < *prev_total_times ||
  149. current_cpu_times < *prev_cpu_times) {
  150. LOG(LS_ERROR) << "Inconsistent time values are passed. ignored";
  151. } else {
  152. const uint64 cpu_diff = current_cpu_times - *prev_cpu_times;
  153. const uint64 total_diff = current_total_times - *prev_total_times;
  154. result = (total_diff == 0ULL ? 0.f :
  155. static_cast<float>(1.0f * cpu_diff / total_diff));
  156. if (result > static_cast<float>(cpus_)) {
  157. result = static_cast<float>(cpus_);
  158. }
  159. *prev_total_times = current_total_times;
  160. *prev_cpu_times = current_cpu_times;
  161. }
  162. return result;
  163. }
  164. float CpuSampler::GetSystemLoad() {
  165. uint32 timenow = Time();
  166. int elapsed = static_cast<int>(TimeDiff(timenow, system_.prev_load_time_));
  167. if (min_load_interval_ != 0 && system_.prev_load_time_ != 0u &&
  168. elapsed < min_load_interval_) {
  169. return system_.prev_load_;
  170. }
  171. #ifdef WIN32
  172. uint64 total_times, cpu_times;
  173. typedef BOOL (_stdcall *GST_PROC)(LPFILETIME, LPFILETIME, LPFILETIME);
  174. typedef NTSTATUS (WINAPI *QSI_PROC)(SYSTEM_INFORMATION_CLASS,
  175. PVOID, ULONG, PULONG);
  176. GST_PROC get_system_times = reinterpret_cast<GST_PROC>(get_system_times_);
  177. QSI_PROC nt_query_system_information = reinterpret_cast<QSI_PROC>(
  178. nt_query_system_information_);
  179. if (get_system_times) {
  180. FILETIME idle_time, kernel_time, user_time;
  181. if (!get_system_times(&idle_time, &kernel_time, &user_time)) {
  182. LOG(LS_ERROR) << "::GetSystemTimes() failed: " << ::GetLastError();
  183. return 0.f;
  184. }
  185. // kernel_time includes Kernel idle time, so no need to
  186. // include cpu_time as total_times
  187. total_times = ToUInt64(kernel_time) + ToUInt64(user_time);
  188. cpu_times = total_times - ToUInt64(idle_time);
  189. } else {
  190. if (nt_query_system_information) {
  191. ULONG returned_length = 0;
  192. scoped_array<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION> processor_info(
  193. new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[cpus_]);
  194. nt_query_system_information(
  195. ::SystemProcessorPerformanceInformation,
  196. reinterpret_cast<void*>(processor_info.get()),
  197. cpus_ * sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION),
  198. &returned_length);
  199. if (returned_length !=
  200. (cpus_ * sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION))) {
  201. LOG(LS_ERROR) << "NtQuerySystemInformation has unexpected size";
  202. return 0.f;
  203. }
  204. uint64 current_idle = 0;
  205. uint64 current_kernel = 0;
  206. uint64 current_user = 0;
  207. for (int ix = 0; ix < cpus_; ++ix) {
  208. current_idle += processor_info[ix].IdleTime.QuadPart;
  209. current_kernel += processor_info[ix].UserTime.QuadPart;
  210. current_user += processor_info[ix].KernelTime.QuadPart;
  211. }
  212. total_times = current_kernel + current_user;
  213. cpu_times = total_times - current_idle;
  214. } else {
  215. return 0.f;
  216. }
  217. }
  218. #endif // WIN32
  219. #if defined(IOS) || defined(OSX)
  220. host_cpu_load_info_data_t cpu_info;
  221. mach_msg_type_number_t info_count = HOST_CPU_LOAD_INFO_COUNT;
  222. if (KERN_SUCCESS != host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO,
  223. reinterpret_cast<host_info_t>(&cpu_info),
  224. &info_count)) {
  225. LOG(LS_ERROR) << "::host_statistics() failed";
  226. return 0.f;
  227. }
  228. const uint64 cpu_times = cpu_info.cpu_ticks[CPU_STATE_NICE] +
  229. cpu_info.cpu_ticks[CPU_STATE_SYSTEM] +
  230. cpu_info.cpu_ticks[CPU_STATE_USER];
  231. const uint64 total_times = cpu_times + cpu_info.cpu_ticks[CPU_STATE_IDLE];
  232. #endif // defined(IOS) || defined(OSX)
  233. #if defined(LINUX) || defined(ANDROID)
  234. if (!sfile_) {
  235. LOG(LS_ERROR) << "Invalid handle for proc/stat";
  236. return 0.f;
  237. }
  238. std::string statbuf;
  239. sfile_->SetPosition(0);
  240. if (!sfile_->ReadLine(&statbuf)) {
  241. LOG_ERR(LS_ERROR) << "Could not read proc/stat file";
  242. return 0.f;
  243. }
  244. unsigned long long user;
  245. unsigned long long nice;
  246. unsigned long long system;
  247. unsigned long long idle;
  248. if (sscanf(statbuf.c_str(), "cpu %Lu %Lu %Lu %Lu",
  249. &user, &nice,
  250. &system, &idle) != 4) {
  251. LOG_ERR(LS_ERROR) << "Could not parse cpu info";
  252. return 0.f;
  253. }
  254. const uint64 cpu_times = nice + system + user;
  255. const uint64 total_times = cpu_times + idle;
  256. #endif // defined(LINUX) || defined(ANDROID)
  257. system_.prev_load_time_ = timenow;
  258. system_.prev_load_ = UpdateCpuLoad(total_times,
  259. cpu_times * cpus_,
  260. &system_.prev_total_times_,
  261. &system_.prev_cpu_times_);
  262. return system_.prev_load_;
  263. }
  264. float CpuSampler::GetProcessLoad() {
  265. uint32 timenow = Time();
  266. int elapsed = static_cast<int>(TimeDiff(timenow, process_.prev_load_time_));
  267. if (min_load_interval_ != 0 && process_.prev_load_time_ != 0u &&
  268. elapsed < min_load_interval_) {
  269. return process_.prev_load_;
  270. }
  271. #ifdef WIN32
  272. FILETIME current_file_time;
  273. ::GetSystemTimeAsFileTime(&current_file_time);
  274. FILETIME create_time, exit_time, kernel_time, user_time;
  275. if (!::GetProcessTimes(::GetCurrentProcess(),
  276. &create_time, &exit_time, &kernel_time, &user_time)) {
  277. LOG(LS_ERROR) << "::GetProcessTimes() failed: " << ::GetLastError();
  278. return 0.f;
  279. }
  280. const uint64 total_times =
  281. ToUInt64(current_file_time) - ToUInt64(create_time);
  282. const uint64 cpu_times =
  283. (ToUInt64(kernel_time) + ToUInt64(user_time));
  284. #endif // WIN32
  285. #ifdef POSIX
  286. // Common to both OSX and Linux.
  287. struct timeval tv;
  288. gettimeofday(&tv, NULL);
  289. const uint64 total_times = tv.tv_sec * kNumMicrosecsPerSec + tv.tv_usec;
  290. #endif
  291. #if defined(IOS) || defined(OSX)
  292. // Get live thread usage.
  293. task_thread_times_info task_times_info;
  294. mach_msg_type_number_t info_count = TASK_THREAD_TIMES_INFO_COUNT;
  295. if (KERN_SUCCESS != task_info(mach_task_self(), TASK_THREAD_TIMES_INFO,
  296. reinterpret_cast<task_info_t>(&task_times_info),
  297. &info_count)) {
  298. LOG(LS_ERROR) << "::task_info(TASK_THREAD_TIMES_INFO) failed";
  299. return 0.f;
  300. }
  301. // Get terminated thread usage.
  302. task_basic_info task_term_info;
  303. info_count = TASK_BASIC_INFO_COUNT;
  304. if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO,
  305. reinterpret_cast<task_info_t>(&task_term_info),
  306. &info_count)) {
  307. LOG(LS_ERROR) << "::task_info(TASK_BASIC_INFO) failed";
  308. return 0.f;
  309. }
  310. const uint64 cpu_times = (TimeValueTToInt64(task_times_info.user_time) +
  311. TimeValueTToInt64(task_times_info.system_time) +
  312. TimeValueTToInt64(task_term_info.user_time) +
  313. TimeValueTToInt64(task_term_info.system_time));
  314. #endif // defined(IOS) || defined(OSX)
  315. #if defined(LINUX) || defined(ANDROID)
  316. rusage usage;
  317. if (getrusage(RUSAGE_SELF, &usage) < 0) {
  318. LOG_ERR(LS_ERROR) << "getrusage failed";
  319. return 0.f;
  320. }
  321. const uint64 cpu_times =
  322. (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * kNumMicrosecsPerSec +
  323. usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
  324. #endif // defined(LINUX) || defined(ANDROID)
  325. process_.prev_load_time_ = timenow;
  326. process_.prev_load_ = UpdateCpuLoad(total_times,
  327. cpu_times,
  328. &process_.prev_total_times_,
  329. &process_.prev_cpu_times_);
  330. return process_.prev_load_;
  331. }
  332. int CpuSampler::GetMaxCpus() const {
  333. return cpus_;
  334. }
  335. int CpuSampler::GetCurrentCpus() {
  336. return sysinfo_->GetCurCpus();
  337. }
  338. ///////////////////////////////////////////////////////////////////
  339. // Implementation of class CpuMonitor.
  340. CpuMonitor::CpuMonitor(Thread* thread)
  341. : monitor_thread_(thread ? thread : Thread::Current()) {
  342. monitor_thread_->SignalQueueDestroyed.connect(
  343. this, &CpuMonitor::OnMessageQueueDestroyed);
  344. }
  345. CpuMonitor::~CpuMonitor() {
  346. Stop();
  347. }
  348. bool CpuMonitor::Start(int period_ms) {
  349. if (!sampler_.Init()) return false;
  350. period_ms_ = period_ms;
  351. if (monitor_thread_) {
  352. monitor_thread_->PostDelayed(period_ms_, this);
  353. }
  354. return true;
  355. }
  356. void CpuMonitor::Stop() {
  357. if (monitor_thread_) {
  358. monitor_thread_->Clear(this);
  359. }
  360. }
  361. void CpuMonitor::OnMessage(Message* msg) {
  362. int max_cpus = sampler_.GetMaxCpus();
  363. int current_cpus = sampler_.GetCurrentCpus();
  364. float process_load = sampler_.GetProcessLoad();
  365. float system_load = sampler_.GetSystemLoad();
  366. SignalUpdate(current_cpus, max_cpus, process_load, system_load);
  367. if (monitor_thread_) {
  368. monitor_thread_->PostDelayed(period_ms_, this);
  369. }
  370. }
  371. } // namespace talk_base