summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--base/process_util_linux.cc5
-rw-r--r--base/process_util_posix.cc53
2 files changed, 53 insertions, 5 deletions
diff --git a/base/process_util_linux.cc b/base/process_util_linux.cc
index 4e0371c..ec45d3f 100644
--- a/base/process_util_linux.cc
+++ b/base/process_util_linux.cc
@@ -322,9 +322,4 @@ bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) {
return true;
}
-int ProcessMetrics::GetCPUUsage() {
- // TODO(port): This needs to be replaced by an call to getrusage().
- return -1;
-}
-
} // namespace base
diff --git a/base/process_util_posix.cc b/base/process_util_posix.cc
index 9c34c6c..a3577aa 100644
--- a/base/process_util_posix.cc
+++ b/base/process_util_posix.cc
@@ -4,12 +4,17 @@
#include "base/process_util.h"
+#include <sys/resource.h>
+#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/basictypes.h"
+#include "base/logging.h"
#include "base/sys_info.h"
+const int kMicrosecondsPerSecond = 1000000;
+
namespace base {
int GetCurrentProcId() {
@@ -46,4 +51,52 @@ void RaiseProcessToHighPriority() {
// 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() {
+ int retval;
+ struct timeval now;
+ struct rusage usage;
+
+ 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<int>((system_time_delta * 100 + time_delta / 2) /
+ time_delta);
+
+ last_system_time_ = system_time;
+ last_time_ = time;
+
+ return cpu;
+}
+
} // namespace base