Computer >> Máy Tính >  >> Lập trình >> Javascript

Phương thức process.cpuUsage () trong Node.js

Phương thức process.argv () được sử dụng để lấy người dùng và việc sử dụng cpu của nó cho quá trình đang chạy hiện tại. Dữ liệu được trả về trong một đối tượng với người dùng thuộc tính và hệ thống. Các giá trị thu được tính bằng micro giây, tức là 10 ^ -6 giây. Các giá trị trả về có thể lớn hơn thời gian thực tế đã trôi qua nếu nhiều lõi đang thực hiện công việc cho quá trình đang chạy.

Cú pháp

process.cpuUsage([previousValue])

Tham số

Phương thức chỉ chấp nhận một tham số duy nhất được định nghĩa bên dưới -

  • Giá trị trước - Đây là một tham số tùy chọn. Đây là giá trị trả về trước đó bằng cách gọi phương thức process.cpuUsage ().

Ví dụ

Tạo một tệp có tên - cpuUsage.js và sao chép đoạn mã bên dưới. Sau khi tạo tệp, sử dụng lệnh sau để chạy mã này như được hiển thị trong ví dụ bên dưới -

node cpuUsage.js

cpuUsage.js

// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Getting the cpu usage details by calling the below method
const usage = process.cpuUsage();

// Printing the cpu usage values
console.log(usage);

Đầu ra

admin@root:~/node/test$ node cpuUsage.js
{ user: 352914, system: 19826 }

Ví dụ

Hãy xem thêm một ví dụ.

// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Getting the cpu usage details by calling the below method
var usage = process.cpuUsage();
// Printing the cpu usage values
console.log("cpu usage before: ", usage);

// Printing the current time stamp
const now = Date.now();

// Looping to delay the process for 100 milliseconds
while (Date.now() - now < 100);

// After using the cpu for nearly 100ms
// calling the process.cpuUsage() method again...
usage = process.cpuUsage(usage);

// Printing the new cpu usage values
console.log("Cpu usage by this process: ", usage);

Đầu ra

admin@root:~/node/test$ node cpuUsage.js
cpu usage before: { user: 357675, system: 32150 }
Cpu usage by this process: { user: 93760, system: 95 }