This article mainly introduces three unknown Node types. js Code optimization methods help you optimize code. If you are interested, refer to Node. the running of js programs may be limited by the CPU or input/output operations and very slow. From the CPU perspective, one of the typical causes of slow running is the unoptimized "Hot Path" (a frequently accessed code ). From the perspective of input and output, the speed limit of the program running may be affected by the underlying operating system, or it may be caused by Node faults. Alternatively, a program that runs slowly may have nothing to do with Node itself. The problem is that external resources, such as database queries or slow API calls, have not been optimized.
In this article, we will focus on identifying and optimizing operations that will cause heavy CPU operations in the code library. At the same time, we will discuss the configuration files for production applications and analyze and make changes that can improve the operational efficiency.
Because of Node's single-threaded nature, it is especially important for the server to avoid heavy CPU loads. Because the time consumed on the CPU will take up the time to respond to other requests. If you notice that your application is slow in response and the CPU usage is always high during this process, analyzing your program helps identify bottlenecks and restore the program to a fast running state.
Analysis Application
The slow program issue in the replication production environment is very difficult to solve and time-consuming. Fortunately, you don't need to do this yourself. You can collect configuration file data on the production server and analyze it offline. Next let's take a look at several analysis methods.
1. Use kernel-level tools
First, you can use kernel-level tools such as DTrace (Solaris, BSD), perf (Linux), or XPerf (Windows) to collect stack trace information from running processes, then generate a flame map. Kernel-level analysis has the least impact on running processes. A flame graph is a vector graph generated based on the call stack that supports zoom-in and zoom-out viewing. Yunong Xiao from Netflix has delivered awesome speeches and tweets for perf in Linux, helping you better understand the technology. If you want to maintain a high throughput in the production program, you can refer to this method.
2,
2. Use the V8 Analyzer
Another option is to directly use the V8 analyzer. This method will share the process with the program, so it will affect the program performance. For this reason, run the V8 analyzer only to capture the relevant output when you encounter such problems. The advantage of this method is that you can use all the analysis tools of Chrome to investigate the program based on the output results (including the flame graph.
Run the following code to test your program:
npm install v8-profiler --save
Then, add the following code to your program:
const profiler = require('v8-profiler')const fs = require('fs')var profilerRunning = falsefunction toggleProfiling () { if (profilerRunning) { const profile = profiler.stopProfiling() console.log('stopped profiling') profile.export() .pipe(fs.createWriteStream('./myapp-'+Date.now()+'.cpuprofile')) .once('error', profiler.deleteAllProfiles) .once('finish', profiler.deleteAllProfiles) profilerRunning = false return } profiler.startProfiling() profilerRunning = true console.log('started profiling')}process.on('SIGUSR2', toggleProfiling)
As long as you send the SIGUSR2 signal to this process, it will start to analyze. Send a SIGUSR2 signal again to stop the analysis (the Code is as follows ).
kill -SIGUSR2 [pid]
The analysis result of this process will be written to the file in the current working path (please make sure this path can be written ). Because this is a programmable interface, you can trigger it at will (using web endpoint, IPC, and so on ). If you have a hunch about when the program gets slower, you can trigger this interface at any time. Automatic triggering is useful to avoid continuous monitoring programs, but it requires you to have a predictive understanding of the capture time and capture time.
Once the configuration file data has been collected, load it into the Chrome development tool and start the analysis!
3. Use Process Manager
Although using the V8 analyzer directly is very effective and customizable, it will enter your code library and add another dependent condition to the project that you may not want. One alternative is to use the process manager, which can wrap your program with various tools when you need to analyze it. An optional tool is the SLC command line tool from StrongLoop.
First, run npm install strongloop-g, and then run the following code:
slc start [/path/to/app]
The above code starts your program in the process manager. You can extract CPU analysis data as needed. To verify and obtain the application id, run:
slc ctl
You will get a running result similar to the following:
Service ID: 1Service Name: my-sluggish-appEnvironment variables: Name Value NODE_ENV productionInstances: Version Agent version Debugger version Cluster size Driver metadata 5.0.1 2.0.2 1.0.0 1 N/AProcesses: ID PID WID Listening Ports Tracking objects? CPU profiling? Tracing? Debugging? 1.1.61022 61022 0 1.1.61023 61023 1 0.0.0.0:3000
Locate the application process id. In this example, the id is 1.1.61023. Now we can start the analysis at any time and run the following code:
slc ctl cpu-start 1.1.61023
When we think we have captured the lagging behavior, we can run the following code to stop the analyzer:
slc ctl cpu-stop 1.1.61023
Run the following code to write a file to the hard disk:
CPU profile written to `node.1.1.61023.cpuprofile`, load into Chrome Dev Tools
Okay, that's it. You can load the file into Chrome for further analysis as in the V8 analyzer.
Make the right decision
In this article, I show three ways to capture CPU usage in the production environment in Node. Which one should you choose? The following are some ideas to help you narrow down your decision scope:
- I need to analyze it for a long time: using kernel-level tools.
- I want to use Chrome development tools: V8 analyzer or Process Manager.
- I want to capture specific behavior in the application: Use the V8 analyzer.
- I don't want to affect program performance: use kernel-level programs
- I hope I don't need a test file to get the program analysis information: Use the Process Manager.
The above is all the content of this article, three Node. js code optimization methods, I hope you can master.