Profile. rb is the profiler prepared for the Ruby program. It can count and output the running time of each method to locate the performance bottleneck of program execution. This time, we will use it to analyze the running time of the script. The usage is simple. You can add the command line option-r profile:
Ruby-r profile rename. rb
After running, the statistical information is output to the standard error output. As shown in:
Profile counts the running time of each method, which is divided into two types. The second calculation is the time from the method call to the method return, which is called the overall time; the first is the time taken to call other methods from the total time, which is called the actual time. The meaning of each field in each line of output information is as follows (from left to right ):
The percentage of execution time of this method to the overall time. The higher the percentage, the more code this line may need to be optimized.
Total time
Total actual time
Number of calls
Average actual time of each call (MS)
Average overall time of each call (MS)
Method Name
It can be seen that most of the script execution time is in a loop. There are two solutions: Eliminate loops or reduce the number of loops. The former is very difficult to implement, and there is no way yet, maybe it is impossible at all. The mapping size in the script is 2685, so every time you modify a file name, you need to execute 2685 cycles and encode and gsub in the loop! All are time-consuming operations. Generally, the length of a file name cannot exceed 30 characters. By traversing each character in the file name, you can reduce the number of cycles to no more than 30 times.
After modifying the code, run the analysis command again. The result is that the script running time is optimized from 379395 seconds to 2418 seconds, and the performance is improved by 156 times to 2 orders of magnitude.