@@ -106,6 +106,7 @@ using v8::Boolean;
106106using v8::Context;
107107using v8::EscapableHandleScope;
108108using v8::Exception;
109+ using v8::Float64Array;
109110using v8::Function;
110111using v8::FunctionCallbackInfo;
111112using v8::FunctionTemplate;
@@ -2220,6 +2221,38 @@ void Hrtime(const FunctionCallbackInfo<Value>& args) {
22202221 fields[2 ] = t % NANOS_PER_SEC;
22212222}
22222223
2224+ // Microseconds in a second, as a float, used in CPUUsage() below
2225+ #define MICROS_PER_SEC 1e6
2226+
2227+ // CPUUsage use libuv's uv_getrusage() this-process resource usage accessor,
2228+ // to access ru_utime (user CPU time used) and ru_stime (system CPU time used),
2229+ // which are uv_timeval_t structs (long tv_sec, long tv_usec).
2230+ // Returns those values as Float64 microseconds in the elements of the array
2231+ // passed to the function.
2232+ void CPUUsage (const FunctionCallbackInfo<Value>& args) {
2233+ uv_rusage_t rusage;
2234+
2235+ // Call libuv to get the values we'll return.
2236+ int err = uv_getrusage (&rusage);
2237+ if (err) {
2238+ // On error, return the strerror version of the error code.
2239+ Local<String> errmsg = OneByteString (args.GetIsolate (), uv_strerror (err));
2240+ args.GetReturnValue ().Set (errmsg);
2241+ return ;
2242+ }
2243+
2244+ // Get the double array pointer from the Float64Array argument.
2245+ CHECK (args[0 ]->IsFloat64Array ());
2246+ Local<Float64Array> array = args[0 ].As <Float64Array>();
2247+ CHECK_EQ (array->Length (), 2 );
2248+ Local<ArrayBuffer> ab = array->Buffer ();
2249+ double * fields = static_cast <double *>(ab->GetContents ().Data ());
2250+
2251+ // Set the Float64Array elements to be user / system values in microseconds.
2252+ fields[0 ] = MICROS_PER_SEC * rusage.ru_utime .tv_sec + rusage.ru_utime .tv_usec ;
2253+ fields[1 ] = MICROS_PER_SEC * rusage.ru_stime .tv_sec + rusage.ru_stime .tv_usec ;
2254+ }
2255+
22232256extern " C" void node_module_register (void * m) {
22242257 struct node_module * mp = reinterpret_cast <struct node_module *>(m);
22252258
@@ -3212,6 +3245,8 @@ void SetupProcessObject(Environment* env,
32123245
32133246 env->SetMethod (process, " hrtime" , Hrtime);
32143247
3248+ env->SetMethod (process, " cpuUsage" , CPUUsage);
3249+
32153250 env->SetMethod (process, " dlopen" , DLOpen);
32163251
32173252 env->SetMethod (process, " uptime" , Uptime);
0 commit comments