// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process_util.h" #include #include #include #include #include "base/basictypes.h" #include "base/logging.h" #include "base/sys_info.h" const int kMicrosecondsPerSecond = 1000000; namespace base { int GetCurrentProcId() { return getpid(); } ProcessHandle GetCurrentProcessHandle() { return GetCurrentProcId(); } int GetProcId(ProcessHandle process) { return process; } ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process), last_time_(0), last_system_time_(0) { processor_count_ = base::SysInfo::NumberOfProcessors(); } // static ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) { return new ProcessMetrics(process); } ProcessMetrics::~ProcessMetrics() { } void EnableTerminationOnHeapCorruption() { // On POSIX, there nothing to do AFAIK. } void RaiseProcessToHighPriority() { // On POSIX, we don't actually do anything here. We could try to nice() or // setpriority() or sched_getscheduler, but these all require extra rights. } namespace { int64 TimeValToMicroseconds(const struct timeval& tv) { return tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec; } } int ProcessMetrics::GetCPUUsage() { struct timeval now; struct rusage usage; int retval = gettimeofday(&now, NULL); if (retval) return 0; retval = getrusage(RUSAGE_SELF, &usage); if (retval) return 0; int64 system_time = (TimeValToMicroseconds(usage.ru_stime) + TimeValToMicroseconds(usage.ru_utime)) / processor_count_; int64 time = TimeValToMicroseconds(now); if ((last_system_time_ == 0) || (last_time_ == 0)) { // First call, just set the last values. last_system_time_ = system_time; last_time_ = time; return 0; } int64 system_time_delta = system_time - last_system_time_; int64 time_delta = time - last_time_; DCHECK(time_delta != 0); if (time_delta == 0) return 0; // We add time_delta / 2 so the result is rounded. int cpu = static_cast((system_time_delta * 100 + time_delta / 2) / time_delta); last_system_time_ = system_time; last_time_ = time; return cpu; } } // namespace base