@@ -106,6 +106,7 @@ using v8::Boolean;
106
106
using v8::Context;
107
107
using v8::EscapableHandleScope;
108
108
using v8::Exception;
109
+ using v8::Float64Array;
109
110
using v8::Function;
110
111
using v8::FunctionCallbackInfo;
111
112
using v8::FunctionTemplate;
@@ -2220,6 +2221,38 @@ void Hrtime(const FunctionCallbackInfo<Value>& args) {
2220
2221
fields[2 ] = t % NANOS_PER_SEC;
2221
2222
}
2222
2223
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
+
2223
2256
extern " C" void node_module_register (void * m) {
2224
2257
struct node_module * mp = reinterpret_cast <struct node_module *>(m);
2225
2258
@@ -3212,6 +3245,8 @@ void SetupProcessObject(Environment* env,
3212
3245
3213
3246
env->SetMethod (process, " hrtime" , Hrtime);
3214
3247
3248
+ env->SetMethod (process, " cpuUsage" , CPUUsage);
3249
+
3215
3250
env->SetMethod (process, " dlopen" , DLOpen);
3216
3251
3217
3252
env->SetMethod (process, " uptime" , Uptime);
0 commit comments