Advertisement

Google Ad Slot: content-top

CodeIgniter Benchmarking


Benchmarking in CodeIgniter is a way to measure the performance of your application.

It helps you find out how much time your code takes to execute and how much memory it uses.

This is especially useful for:

  • Optimizing slow queries.
  • Checking how fast controllers or functions run.
  • Improving the overall performance of your web application.

CodeIgniter has a Benchmarking Class that runs automatically when the framework starts.

By default, CodeIgniter marks two points:

  • total_execution_time_start → when the framework starts.
  • total_execution_time_end → when the system execution ends.

You can add your own markers anywhere in your code to measure execution time between them.

🔹 Adding Benchmark Markers

Use the mark() function to set a benchmark point.

$this->benchmark->mark('start_point');

// Your code here
for ($i = 0; $i < 1000000; $i++) {
    // some logic
}

$this->benchmark->mark('end_point');

🔹 Calculating Elapsed Time

After setting markers, calculate the execution time like this:

echo $this->benchmark->elapsed_time('start_point', 'end_point');

✅ This will show the time taken (in seconds) between start_point and end_point.

🔹 Checking Memory Usage

You can also check memory usage:

echo $this->benchmark->memory_usage();

This tells you how much memory your script is consuming at that point.

🔹 Example

class Test extends CI_Controller {

    public function index()
    {
        $this->benchmark->mark('code_start');

        // Example task
        for ($i = 0; $i < 500000; $i++) {
            $x = $i * $i;
        }

        $this->benchmark->mark('code_end');

        echo "Execution Time: " . $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds";
        echo "<br>Memory Usage: " . $this->benchmark->memory_usage();
    }
}

👉 This example will display how much time the loop took and how much memory it consumed.

🔹 Benchmarking in Views

You can also use special placeholders inside views:

// Displays total execution time
{elapsed_time}

// Displays memory used
{memory_usage}

✅ These are useful for showing performance details at the bottom of your pages.