search
HomeBackend DevelopmentPHP TutorialCI framework source code reading notes 5 Benchmark test BenchMark.php, cibenchmark.php_PHP tutorial

CI framework source code reading notes 5 benchmark test BenchMark.php, cibenchmark.php

In the previous blog (CI framework source code reading notes 4 boot file CodeIgniter.php), we It has been seen that the core functions of the core processes in CI are completed by different components. These components are similar to individual modules. Different modules complete different functions. Each module can call each other and together form the core skeleton of CI.

Starting from this article, we will further analyze the implementation details of each component and go deep into the black box of the CI core (after research, it should actually be a white box, but only for applications, it should be regarded as a black box). In order to better understand and grasp this framework.

As usual, before we start, we paste the incomplete core component diagram in CI:

Since BenchMark is the first core component loaded in CI, our analysis starts with this component first. The meaning of BenchMark is very clear. Students who have used the BenchMark tool should know that this is a benchmark component. Since it is BenchMark, we can boldly guess that the main function of the BM component is to record the running time, memory usage, CPU usage, etc. of the program.

Look at the class diagram first:

The structure of this component is relatively simple, with only one marker internal variable and three external interfaces:

<span>1</span> <span>Elapsed_time
</span><span>2</span> <span>Mark
</span><span>3</span> Memory_usage

Expand each one below:

1.mark

The signature of the function is:

<span>function</span> mark(<span>$name</span>)

This function accepts a string type parameter, and the implementation is simpler, with only one sentence:

<span>$this</span>->marker[<span>$name</span>] = <span>microtime</span>();

In other words, this function is only used to record the time point at which the function is called.

It is worth noting that due to the special processing in Controller (we will explain it in detail later), you can use $this->benchmark->mark($name); to add running time points, for example:

$this->benchmark->mark("function_test_start");
$this->_test();
$this->benchmark->mark("function_test_end");
print_r($this->benchmark);

Among them, function_test_start and function_test_end are used to record the start and end time points of function calls respectively

Printed results:

Now to calculate the function call time, you need to use the second function elapsed_time of the BenchMark component

2. elapsed_time

The signature of the function is:

<span>function</span> elapsed_time(<span>$point1</span> = '', <span>$point2</span> = '', <span>$decimals</span> = 4)

All three parameters are optional

(1). If $point1 is empty, return ‘{elapsed_time}’

if ($point1 == '') {
     return '{elapsed_time}';
}

Nani! It should obviously return time, but instead it returns a string, and it’s so strange (similar to smarty tags). In fact, in the Output component, {elapsed_time} will be replaced. Let’s take a look at the replacement method for now:

$elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
$output = str_replace('{elapsed_time}', $elapsed, $output);

In other words, when no parameters are specified, what is actually obtained by calling this function is the time difference from the time point of total_execution_time_start to the time point of total_execution_time_end. Furthermore, since total_execution_time_start is the first mark point set after BM is loaded (total_execution_time_end is not defined and returns the current time point), what this function returns is actually the loading and running time of the system.

(2). If an unknown mark point is called. The result is unknown and empty is returned directly:

if ( ! isset($this->marker[$point1]))
{
    return '';
}

(3). If the mark point of $point2 is not set, the mark point of $point2 is set to the current time point.

if ( ! isset($this->marker[$point2]))
{
    $this->marker[$point2] = microtime();
}

(4). The time difference between the last two mark points returned:

list($sm, $ss) = explode(' ', $this->marker[$point1]);
list($em, $es) = explode(' ', $this->marker[$point2]);

return number_format(($em + $es) - ($sm + $ss), $decimals);

Looking at the previous example, here we can call:

<span>echo</span> <span>$this</span>->benchmark->elapsed_time("function_test_start","function_test_end");

Get the execution time of the function.

3. memory_usage

This function returns the memory usage of the system (MB unit). Like {elapsed_time}, the {memory_usage} returned by this function will also be replaced in Output. :

<span>$memory</span>  = ( ! <span>function_exists</span>('memory_get_usage')) ? '0' : <span>round</span>(memory_get_usage()/1024/1024, 2).'MB'<span>;
</span><span>$output</span> = <span>str_replace</span>('{memory_usage}', <span>$memory</span>, <span>$output</span>);

Since the BenchMark component itself is relatively simple, we will not explain it further.

Finally, paste the source code of this component:

<?<span>php

</span><span>class</span><span> CI_Benchmark {

    </span><span>/*</span><span>*
     * List of all benchmark markers and when they were added
     *
     * @var array
     </span><span>*/</span>
    <span>var</span> <span>$marker</span> = <span>array</span><span>();

    </span><span>/*</span><span>*
     * Set a benchmark marker
     *
     * @access    public
     * @param    string    $name    name of the marker
     * @return    void
     </span><span>*/</span>
    <span>function</span> mark(<span>$name</span><span>)
    {
        </span><span>$this</span>->marker[<span>$name</span>] = <span>microtime</span><span>();
    }

    </span><span>/*</span><span>*
     * Calculates the time difference between two marked points.
     * If the first parameter is empty this function instead returns the {elapsed_time} pseudo-variable. This permits the full system
     * @access    public
     * @param    string    a particular marked point
     * @param    string    a particular marked point
     * @param    integer    the number of decimal places
     * @return    mixed
     </span><span>*/</span>
    <span>function</span> elapsed_time(<span>$point1</span> = '', <span>$point2</span> = '', <span>$decimals</span> = 4<span>)
    {
        </span><span>if</span> (<span>$point1</span> == ''<span>)
        {
            </span><span>return</span> '{elapsed_time}'<span>;
        }

        </span><span>if</span> ( ! <span>isset</span>(<span>$this</span>->marker[<span>$point1</span><span>]))
        {
            </span><span>return</span> ''<span>;
        }

        </span><span>if</span> ( ! <span>isset</span>(<span>$this</span>->marker[<span>$point2</span><span>]))
        {
            </span><span>$this</span>->marker[<span>$point2</span>] = <span>microtime</span><span>();
        }

        </span><span>list</span>(<span>$sm</span>, <span>$ss</span>) = <span>explode</span>(' ', <span>$this</span>->marker[<span>$point1</span><span>]);
        </span><span>list</span>(<span>$em</span>, <span>$es</span>) = <span>explode</span>(' ', <span>$this</span>->marker[<span>$point2</span><span>]);

        </span><span>return</span> <span>number_format</span>((<span>$em</span> + <span>$es</span>) - (<span>$sm</span> + <span>$ss</span>), <span>$decimals</span><span>);
    }

    </span><span>/*</span><span>*
     * Memory Usage
     * This function returns the {memory_usage} pseudo-variable.
     </span><span>*/</span>
    <span>function</span><span> memory_usage()
    {
        </span><span>return</span> '{memory_usage}'<span>;
    }

}</span>

How to do unit testing using PHP CI framework? Is it better to use the one that comes with CI or phpunit?

phpunit

The ci framework has requirements for the mysql version. Why will an error be reported when using mysql55?

Mysql.ci, which is not the latest, is currently being used normally.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907043.htmlTechArticleCI framework source code reading notes 5 Benchmark test BenchMark.php, cibenchmark.php Previous blog (CI framework source code reading Note 4 Boot file CodeIgniter.php), we have seen: CI core...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor