@@ -102,6 +102,7 @@ using v8::Boolean;
102102using v8::Context;
103103using v8::EscapableHandleScope;
104104using v8::Exception;
105+ using v8::Float64Array;
105106using v8::Function;
106107using v8::FunctionCallbackInfo;
107108using v8::FunctionTemplate;
@@ -2203,6 +2204,38 @@ void Hrtime(const FunctionCallbackInfo<Value>& args) {
22032204 args.GetReturnValue ().Set (tuple);
22042205}
22052206
2207+ // Microseconds in a second, as a float, used in CPUUsage() below
2208+ #define MICROS_PER_SEC 1e6
2209+
2210+ // CPUUsage use libuv's uv_getrusage() this-process resource usage accessor,
2211+ // to access ru_utime (user CPU time used) and ru_stime (system CPU time used),
2212+ // which are uv_timeval_t structs (long tv_sec, long tv_usec).
2213+ // Returns those values as Float64 microseconds in the elements of the array
2214+ // passed to the function.
2215+ void CPUUsage (const FunctionCallbackInfo<Value>& args) {
2216+ uv_rusage_t rusage;
2217+
2218+ // Call libuv to get the values we'll return.
2219+ int err = uv_getrusage (&rusage);
2220+ if (err) {
2221+ // On error, return the strerror version of the error code.
2222+ Local<String> errmsg = OneByteString (args.GetIsolate (), uv_strerror (err));
2223+ args.GetReturnValue ().Set (errmsg);
2224+ return ;
2225+ }
2226+
2227+ // Get the double array pointer from the Float64Array argument.
2228+ CHECK (args[0 ]->IsFloat64Array ());
2229+ Local<Float64Array> array = args[0 ].As <Float64Array>();
2230+ CHECK_EQ (array->Length (), 2 );
2231+ Local<ArrayBuffer> ab = array->Buffer ();
2232+ double * fields = static_cast <double *>(ab->GetContents ().Data ());
2233+
2234+ // Set the Float64Array elements to be user / system values in microseconds.
2235+ fields[0 ] = MICROS_PER_SEC * rusage.ru_utime .tv_sec + rusage.ru_utime .tv_usec ;
2236+ fields[1 ] = MICROS_PER_SEC * rusage.ru_stime .tv_sec + rusage.ru_stime .tv_usec ;
2237+ }
2238+
22062239extern " C" void node_module_register (void * m) {
22072240 struct node_module * mp = reinterpret_cast <struct node_module *>(m);
22082241
@@ -3153,6 +3186,8 @@ void SetupProcessObject(Environment* env,
31533186
31543187 env->SetMethod (process, " hrtime" , Hrtime);
31553188
3189+ env->SetMethod (process, " cpuUsage" , CPUUsage);
3190+
31563191 env->SetMethod (process, " dlopen" , DLOpen);
31573192
31583193 env->SetMethod (process, " uptime" , Uptime);
0 commit comments