Sharpen Your Code with Benchmarking in PHP

Sharpen Your Code with Benchmarking in PHP

ny software product must successfully pass the optimization step before it can hit the market and become a reference product. Finding memory leaks and increasing a product’s performance is a delicate job that takes many hours of work and many human resources. Benchmarking is an important step in the optimization puzzle, because it can test both individual chunks of code and the entire codebase, and provides reports and statistics that reveal the true runtime parameters and performance.

In PHP you can use the Benchmark package—a PEAR package used to benchmark PHP scripts or functions calls. The latest released version is 1.2.7 (stable); after downloading the package, you can install it like this:

   >> pear install Benchmark-1.2.7

To illustrate the Benchmark package’s capabilities you’ll see two different solutions (iterative and recursive) for the classical problem of generating Fibonacci numbers. The complete problem description is beyond the scope of this article, but it’s a very common problem. If you are not familiar with Fibonacci generation, or you just want to re-familiarize yourself with the Fibonacci sequence, you can find more information here.

The Class Trees for Benchmark PEAR
The package has a small set of flexible classes that you use to perform benchmark timing:

  • Benchmark_Timer
  • Benchmark_Iterate
  • Benchmark_Profiler

This article discusses each class, shows its commonly-used methods, and provides an example of using it.

The Benchmark_Timer Class
The Benchmark_Timer class provides a set of methods that return highly-accurate timing information. The prototypes for the most used methods of this class are:

  • void start(): Set the start time of the marker.
  • void stop(): Set the stop time of the marker.
  • void setMarker(string $name): Sets a marker. The $name parameter represents the name of the marker to set.
  • void display([boolean $showTotal = FALSE], [string $format = ‘auto’]): This function returns formatted information. If is set to true, the $showTotal parameter outputs verbose information. The $format parameter controls the desired output format (auto (the default), plain, or html). When the value is auto the PEAR implementation chooses between plain and html; in most cases it chooses plain.
  • array getProfiling(): Returns the profiler info as an associative array. The $profiling[x][‘name’] value represents the name of marker x; the $profiling[x][‘time’] value represents the time index of marker x; the $profiling[x][‘diff’] value represents the execution time from marker x-1 to marker x; and the $profiling[x][‘total’] value represents the total execution time up to marker x.

Benchmarking Fibonacci (Iterative Solution)
This example applies the Benchmark_Timer class to the iterative solution for the Fibonacci numbers, providing formatted timing information:

   start();               $a=0;$b=1;               for ($i = 0; $i < 10; $i++) {         $s=$a+$b;                  //Set the markers fibonacci         $timer->setMarker('fibonacci'.$i);                      $a=$b;         $b=$s;      }                //Set "Stop" marker      $timer->stop();               //Returns formatted informations      $timer->display();                echo '
';               //Get the profiler info as an associative array      $profiling = $timer->getProfiling();                //Display all the information: name,       // time, difference between two        //consecutive markers and total time      print_r($profiling[1]);      print_r($profiling[2]);      print_r($profiling[3]);      echo '

'; } fibonacci(); ?>The code sets a start marker, and then begins a loop that generates the first 10 numbers in the Fibonacci series. After each generation, it sets a marker named “fibonacci” plus the loop counter value (fibonacci1, fibonacci2, etc.).

Listing 1 contains similar code that benchmarks the recursive Fibonacci solution.

Benchmarking Output
Both the iterative and recursive Fibonacci programs output the results in two forms: a formatted table, and as a raw associative array.

The formatted table results show each marker name, the elapsed time when that marker was reached (time index), the time required to reach that marker from the previous marker (ex time), and the percentage of the total time required to reach that marker from the previous marker (%).

The iterative result is:

  Time Index Ex Time Percentage
Start 1209633208.32539500 0.00%
fibonacci0 1209633208.32546500 0.000070 22.88%
fibonacci1 1209633208.32549400 0.000029 9.48%
fibonacci2 1209633208.32551600 0.000022 7.19%
fibonacci3 1209633208.32553900 0.000023 7.52%
fibonacci4 1209633208.32556200 0.000023 7.52%
fibonacci5 1209633208.32558600 0.000024 7.84%
fibonacci6 1209633208.32560800 0.000022 7.19%
fibonacci7 1209633208.32563100 0.000023 7.52%
fibonacci8 1209633208.32565600 0.000025 8.17%
fibonacci9 1209633208.32567800 0.000022 7.19%
Stop 1209633208.32570100 0.000023 7.52%
Total 0.000306 100.00%

The associative array contains the same information in a machine-usable form.

   Array   (       [name] => fibonacci0       [time] => 1209633208.32546500       [diff] => 0.000070       [total] => 0.000070   )   Array   (       [name] => fibonacci1       [time] => 1209633208.32549400       [diff] => 0.000029       [total] => 0.000099   )   Array   (       [name] => fibonacci2       [time] => 1209633208.32551600       [diff] => 0.000022       [total] => 0.000121   )

The recursive result is:

  Time Index Ex Time Percentage
Start 1209633188.10306000 0.00%
fibonacci0 1209633188.10322500 0.000165 7.83%
fibonacci1 1209633188.10330500 0.000080 3.80%
fibonacci2 1209633188.10335800 0.000053 2.52%
fibonacci3 1209633188.10343000 0.000072 3.42%
fibonacci4 1209633188.10350000 0.000070 3.32%
fibonacci5 1209633188.10359200 0.000092 4.37%
fibonacci6 1209633188.10371600 0.000124 5.89%
fibonacci7 1209633188.10388300 0.000167 7.93%
fibonacci8 1209633188.10415100 0.000268 12.72%
fibonacci9 1209633188.10455300 0.000402 19.08%
Stop 1209633188.10516700 0.000614 29.14%
Total 0.002107 100.00%

Again, the associative array contains the same information in a machine-usable form.

   Array   (       [name] => fibonacci0       [time] => 1209633188.10322500       [diff] => 0.000165       [total] => 0.000165   )   Array   (       [name] => fibonacci1       [time] => 1209633188.10330500       [diff] => 0.000080       [total] => 0.000245   )   Array   (       [name] => fibonacci2       [time] => 1209633188.10335800       [diff] => 0.000053       [total] => 0.000298   )

As you can see, the timer provides fine-grained results that you can control using the marker capabilities. In most cases, however, you are likely to be less interested in benchmarking individual lines of code and more interested in benchmarking distinct functions, particularly when you can do that without modifying the function code itself. For that, you use the Benchmark_Iterate class.

The Benchmark_Iterate Class
The Benchmark_Iterate class provides two methods for benchmarking a function:

  • void run(): Benchmarks a function.
  • array get([ $simple_output = false]): Returns the benchmark results. In the results, the code $result[x] represents the execution time of iteration x, $result[‘iterations’] represents the number of iterations and $result[‘mean’] represents the mean execution time.

Before attempting to benchmark a complex function, here’s a simple example that should clarify the benchmarking process. This example defines a function, and then calls it four times using the run method. Finally, it outputs the results:

   ';   }      //Benchmarks the example function   $benchmark->run(4, 'example', 'Octavia');      //Returns benchmark result   $result = $benchmark->get();      echo 'The number of iterations is '.$result['iterations'].'
'; echo 'The mean is: '.$result['mean']; ?>

When you run this application, the output is:

   Octavia   Octavia   Octavia   Octavia   The number of iterations is 4   The mean is: 0.000064

With that simple example in hand, Listing 2 shows a slightly more complex example that applies the Benchmark_Iterate class to the iterative Fibonacci solution, while Listing 3 applies it to the recursive Fibonacci solution. The programs return these results:

Iterative Result

   1 1 2 3 5 8 13 21 34 55 89    The execution time of 1 iteration: 0.000223   The number of iterations is: 1   The mean is: 0.000223

The Recursive Result

   1 1 2 3 5 8 13 21 34 55 89    The execution time of 1 iteration is: 0.001135   The number of iterations is: 1   The mean is: 0.001135

The Benchmark_Profiler Class
The Benchmark_Profiler class provides a set of methods that return formatted profiling information. The prototypes of the most used methods of this class are:

  • void enterSection(string $name): This function enters a code section. The $name parameter represents the name of the code section.
  • void leaveSection(string $name): This function leaves a code section. The $name parameter represents the name of the code section.
  • void display([string $format = ‘auto’]): This function returns formatted profiling information. The $format parameter represents the desired output format: auto (the default), plain or html.

Here’s the code to apply the Benchmark_Profiler class to the iterative and recursive Fibonacci solutions:

      // Iterative version   enterSection('fibonacci'.$i);                $s=$a+$b;          $a=$b;          $b=$s;                //Leaves code section          $profiler->leaveSection('fibonacci'.$i);            }             //Returns formatted profiling information      $profiler->display();      return;   }   fibonacci();   ?>   // Recursive version   =0)and($n<2))      {         return 1;      }      else       {         return fibonacci($n-1)+fibonacci($n-2);      }   }      global $profiler;      for ($i = 0; $i < 10; $i++) {         //Enters code section      $profiler->enterSection('fibonacci'.$i);         fibonacci($i).'
'; //Leaves code section $profiler->leaveSection('fibonacci'.$i); } //Returns formatted profiling information $profiler->display(); return; ?>

Result Comparison
The iterative result is:

  Total Ex. Time Calls Percentage Callers
fibonacci0 0.00025200843811035 1 N/A Global (1)
fibonacci1 4.6968460083008E-005 1 N/A Global (1)
fibonacci2 3.814697265625E-005 1 N/A Global (1)
fibonacci3 5.1021575927734E-005 1 N/A Global (1)
fibonacci4 5.2928924560547E-005 1 N/A Global (1)
fibonacci5 5.6028366088867E-005 1 N/A Global (1)
fibonacci6 3.7908554077148E-005 1 N/A Global (1)
fibonacci7 4.0054321289063E-005 1 N/A Global (1)
fibonacci8 3.6954879760742E-005 1 N/A Global (1)
fibonacci9 0.00029301643371582 1 N/A Global (1)

The recursive result is:

  Total Ex. Time Calls % Callers
fibonacci0 0.0001368522644043 1 N/A Global (1)
fibonacci1 0.00031614303588867 1 N/A Global (1)
fibonacci2 8.4877014160156E-005 1 N/A Global (1)
fibonacci3 7.9870223999023E-005 1 N/A Global (1)
fibonacci4 0.00011897087097168 1 N/A Global (1)
fibonacci5 0.0001227855682373 1 N/A Global (1)
fibonacci6 0.00016498565673828 1 N/A Global (1)
fibonacci7 0.00038599967956543 1 N/A Global (1)
fibonacci8 0.00036907196044922 1 N/A Global (1)
fibonacci9 0.00057005882263184 1 N/A Global (1)

Getting Benchmark Results Graphically
Getting raw numbers is useful, but often it’s more useful to view benchmarking information in a more palatable form, such as bar or pie charts. You can add graphical capabilities to the Timer tests by extending the fibonacci_iterative_timer.php application, using SVG to obtain a bar/pie chart image that visually shows the time required to run each iteration of the main loop. To do that, you plot the last column from the Timer Results table—giving a visual representation of the “ex time” column:

   start();               $a=0;$b=1;               for ($i = 0; $i < 15; $i++) {         $s=$a+$b;                  //Set the markers         $timer->setMarker('f'.$i);                  $a=$b;         $b=$s;      }                //Set "Stop" marker      $timer->stop();               //Returns formatted informations      echo '';      echo '';      echo '';      echo '';      echo '';      echo '
'; $timer->display(); echo ''; //Get the profiler info as an associative array $profiling = $timer->getProfiling(); //serialize the $profiling $ser = serialize($profiling); // Display all the information: name, time, // difference between two consecutive // markers, and total time echo ""; echo '
'; } //start the process fibonacci(); ?>
 
Figure 1. Graphical Representation of Benchmark Results: This view shows the raw data and superimposed pie and bar charts for 15 iterations of the Fibonacci method.

The preceding code outputs an HTML page containing a table with the raw profiling information you’ve already seen. It uses that to generate two SVG-formatted charts (see Listing 4), which it displays using the Adobe SVG player in the right column of the table.

Figure 1 shows the table the code returns, letting users view possible results for 15 Fibonacci iterations.

As you can see, adding benchmarking in PHP using this PEAR is a simple and linear task. It’s not limited to new code, either; implementing benchmarking for your existing PHP code doesn’t require much time, and the results are easy to understand and process—leaving few excuses for not optimizing your PHP applications! What you might consider an unnecessary step now, can really make a big difference later.

devx-admin

devx-admin

Share the Post:
Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions