Optimized Ruby script efficiency instance sharing

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.