Table of Contents
Clock Beat
Get system clock tick information Ticks
Timer function
总结
Home Backend Development PHP Tutorial Detailed explanation of the high-precision timer HRTime extension in PHP

Detailed explanation of the high-precision timer HRTime extension in PHP

Jul 10, 2021 pm 03:12 PM
php

I don’t know if you still remember the stopwatch the teacher brought during the physical education test in school? When the gunshot sounded, we started running, and the stopwatch started. When we passed the finish line, the teacher would press the button to record our results. This is a typical timer application. What we are going to learn today is actually a functional extension similar to the stopwatch of this sports test. It is the HRTime extension of PHP.

Clock Beat

First of all, we need to understand what is the clock beat of the system. When the Linux system starts, a clock metronome will be started at the same time to measure timing in nanoseconds, and the real name of our HRTime extension is the High-Precision Time extension. In other words, it is a clock metronome based on the operating system that can measure timing in nanoseconds.

1 second = 1000 milliseconds = 1000000 microseconds = 1000000000 nanoseconds. This is the relationship between seconds, milliseconds, microseconds and nanoseconds. You can see how high its accuracy is. 1 second is equal to 1 billion nanoseconds, so we can get a very precise count of time intervals.

The HRTime extension can be downloaded and installed directly from PECL, and it is no different from other ordinary extensions.

Get system clock tick information Ticks

Let’s first look at how to get the clock tick of the operating system, which is this Ticks. Regarding its content, I believe many students have already come into contact with it when learning operating systems. Here we look at how to obtain it using the HRTime extension.

print_r(hrtime());
// Array
// (
//     [0] => 3758
//     [1] => 407409171
// )

echo hrtime(true), PHP_EOL;
// 3758407428932
Copy after login

hrtime() This function has been integrated into the default PHP environment after PHP7. It does not require the HRTime extension to be used. This function returns an array without parameters. The 0th item is the number of seconds since the system was started, and the 1st item is the corresponding nanosecond count. If true is set to its parameter, it will directly return the actual nanosecond timestamp concatenated with seconds and nanoseconds.

echo HRTime\PerformanceCounter::getFrequency(), PHP_EOL; // 1000000000
echo HRTime\PerformanceCounter::getTicks(), PHP_EOL; // 3758428256236
echo HRTime\PerformanceCounter::getTicksSince(1212), PHP_EOL; // 3758428257494

$a = HRTime\PerformanceCounter::getTicks();
echo HRTime\PerformanceCounter::getTicksSince($a), PHP_EOL; // 412
Copy after login

The next three functions are the static functions of the PerformanceCounter object in the HRTime extension. The PerformanceCounter object means a performance counter, and getFrequency() represents the timer frequency (in ticks/second). It can be seen that it returns the nanosecond unit, which is 1 billion. getTicks() returns the current clock tick time. It can be seen that the result of it is the same as the hrtime(true) function, which is the clock tick time returned after the system is started. The getTicksSince() method returns the time interval based on the specified number of nanoseconds, which is similar to date_diff(). In fact, it is like our time() - time() operation. Through this method, you can get the time interval between two runs of a piece of code, and the unit is nanoseconds.

Timer function

The next step is the focus of our article, which is the implementation of the timer function. As mentioned above, using getTickSince() can actually monitor the running time interval of a piece of code, but what you will learn below will be more powerful.

$c = new HRTime\StopWatch;

$c->start();
for ($i = 0; $i < 1024*1024; $i++);
echo &#39;isRunning: &#39;, $c->isRunning(), PHP_EOL; // isRunning: 1
$c->stop();

echo 'Time NS: ', $c->getLastElapsedTime(HRTime\Unit::NANOSECOND), PHP_EOL;
echo 'Time US: ', $c->getLastElapsedTime(HRTime\Unit::MICROSECOND), PHP_EOL;
echo 'Time MS: ', $c->getLastElapsedTime(HRTime\Unit::MILLISECOND), PHP_EOL;
echo 'Time S: ', $c->getLastElapsedTime(HRTime\Unit::SECOND), PHP_EOL;
// Time NS: 6929888
// Time US: 6929.888
// Time MS: 6.929888
// Time S: 0.006929888

echo 'Ticks: ',$c->getLastElapsedTicks(), PHP_EOL;
// Ticks: 6929888

echo 'isRunning: ',$c->isRunning(), PHP_EOL;
//
Copy after login

We need to instantiate a StopWatch object and then call its start() method so that a timer is started. The English meaning of StopWatch itself is the meaning of timer, so this object is specially designed to serve the operation of timer. Through the isRunning() method, we can determine whether the current timer is running. In fact, it is to determine whether the current timer is after a start() method. If it is not within the scope of start() and stop(), then it will return false. In the test code, we run an empty loop of 1024*1024 and then use the stop() method to end the timer.

As can be seen from the code, getLastElapsedTime() is to obtain the time interval information between the start() and stop() of our code above. Its parameters can be specified as seconds and milliseconds. , microsecond, nanosecond. The meaning of this method itself is to obtain the running time of the last interval. getLastElapsedTicks() obtains the clock tick information of the last interval. Since there are four words [last time], it means that this object can be called multiple times for segmented timing. Moreover, it can still summarize multiple different timings to obtain all time interval information.

// 不在计时范围内
for ($i = 0; $i < 1024*1024; $i++);

$c->start();
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();

echo 'Time NS: ', $c->getLastElapsedTime(HRTime\Unit::NANOSECOND), PHP_EOL;
echo 'Time US: ', $c->getLastElapsedTime(HRTime\Unit::MICROSECOND), PHP_EOL;
echo 'Time MS: ', $c->getLastElapsedTime(HRTime\Unit::MILLISECOND), PHP_EOL;
echo 'Time S: ', $c->getLastElapsedTime(HRTime\Unit::SECOND), PHP_EOL;
// Time NS: 7154010
// Time US: 7154.01
// Time MS: 7.15401
// Time S: 0.00715401

echo 'All Time NS: ', $c->getElapsedTime(HRTime\Unit::NANOSECOND), PHP_EOL;
echo 'All Time US: ', $c->getElapsedTime(HRTime\Unit::MICROSECOND), PHP_EOL;
echo 'All Time MS: ', $c->getElapsedTime(HRTime\Unit::MILLISECOND), PHP_EOL;
echo 'All Time S: ', $c->getElapsedTime(HRTime\Unit::SECOND), PHP_EOL;
// All Time NS: 14083898
// All Time US: 14083.898
// All Time MS: 14.083898
// All Time S: 0.014083898

echo 'All Ticks: ', $c->getElapsedTicks(), PHP_EOL;
// All Ticks: 14083898
Copy after login

In this code, we inserted a loop test code between the two timing test codes, which will not be counted in the timing data. Then, we restart() to start a new timing. At the end, we obtain the total timing time through getElapsedTime() and getElapsedTicks(). It can be seen that the above 6929888 plus this time 7154010 result in exactly 14083898 . The middle section of loop code that is not in the timer is not included in the total timing time.

Recommended learning: "PHP Video Tutorial"

总结

是不是很有意思,它的作用真的和我们的体育老师所用的那个秒表一模一样,老师们的秒表也都是可以按多次记录第1名到最后1名的全部跑步成绩,并且最后还有一个总的时间,而在代码中我们也是完全相似的操作。这个扩展对于精细的性能调试非常有用,而且也能够针对一些需要这种高精度时间差的业务进行相关的开发。

测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202010/source/3.学习PHP中的高精度计时器HRTime扩展.php
参考文档:
https://www.php.net/manual/zh/book.hrtime.php
Copy after login

The above is the detailed content of Detailed explanation of the high-precision timer HRTime extension in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles