Time with milliseconds php

PHP microtime() Function

The microtime() function returns the current Unix timestamp with microseconds.

Syntax

Parameter Values

Parameter Description
return_float Optional. When set to TRUE it specifies that the function should return a float, instead of a string. Default is FALSE

Technical Details

Return Value: Returns the string «microsec sec» by default, where sec is the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and microsec is the microseconds part. If the return_float parameter is set to TRUE, it returns a float representing the current time in seconds since the Unix epoch accurate to the nearest microsecond
PHP Version: 4+
PHP Changelog: PHP 5.0: Added the return_float parameter

❮ PHP Date/Time Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP microtime: How To Work With Different Time Units

Position Is Everything

Php microtime function

The PHP microtime function is the one that returns the current Unix timestamp with microseconds. And interestingly, you can use the said function to get time in other units as well, such as seconds. So, here you’ll see how the PHP microtime works, how you can use the same for converting time units, and which other function returns time in seconds.

Continue reading to fulfill the time requirements of your program effectively.

What Is microtime in PHP?

The PHP microtime is a built-in function that returns the current Unix timestamp in the “msec sec” format. Here, the “sec” represents the seconds, and the “msec” represents the microseconds after being converted into seconds. The given function accepts a single optional boolean argument “as_float.”

So, the result returned by the microtime in PHP can be read as “microseconds_as_seconds seconds.” Also, you can’t say that the microtime() function returns the current time in microseconds. Furthermore, if you pass “true” to the PHP microtime function, you’ll get the current time in seconds only.

Coding Examples

The following coding examples have been created to show you how to use the microtime function. Plus, you’ll be able to see the difference in the outputs based on the argument passed to the given function.

Читайте также:  Cyberforum ru cpp beginners

– PHP microtime Function With Zero Arguments

For example, you want to display the current time in the “microseconds_as_seconds seconds.” Here you’ll simply need to call the microtime() function without passing any arguments.

Please see the below one-liner code to get current time with microseconds:

// using the microtime function
echo microtime();
// output: 0.28552700 1642373103
?>

– Passing True to the PHP microtime Function

For instance, you want to get the current time in seconds. You need to use the PHP microtime function by passing “true” as an argument.

Please have a look at this code block that compares the results obtained before and after passing “true” as an argument:

$msec_sec = microtime();
echo “Time as msec sec: $msec_sec
”;
// output: Time as msec sec: 0.19812600 1642423688
$seconds = microtime(true);
echo “Time in seconds: $seconds”;
// output: Time in seconds: 1642423688.1981
?>

Increase the Precision in Seconds

Are you looking for a more precise time returned by the microtime(true) function? Well, it would be beneficial to note that the number of digits returned by the microtime(true) function depends on the value of the “precision” directive in the php.ini file. The said directive has its default value set to “14.” But if you want to have more digits, you can call the ini_set() function to set your desired number of digits.

– Coding Example

For instance, you want to set the precision to 16 digits instead of 14. Therefore, you’ll call the ini_set() function by passing the “precision” and “16” as arguments. Later, you’ll call the microtime(true) function to get the current time in seconds with more precision.

The coding instructions given here will assist you in increasing the precision:

// setting the precision to 16
ini_set(“precision”, 16);
// executing the microtime(true) function
echo microtime(true);
// output: 1642439657.329814
?>

Get PHP Timestamp Milliseconds

Would you like to have PHP time in milliseconds? Indeed, you can get the time in milliseconds by using the result returned by the PHP microtime function. All that you’ll need to do is to multiply the output generated by the microtime(true) function by 1000. You shouldn’t doubt the process because it is a basic mathematics formula, and it is a fact that a second is 1000 times bigger than a millisecond.

– Coding Example

Suppose you have a program that requires time in milliseconds. So, you’ll simply execute the PHP microtime function by passing true as an argument. Consequently, you’ll get the current time in seconds, and then you’ll multiply the obtained seconds by 1000 to get PHP time in milliseconds.

The code block shared below will be helpful for you in understanding the entire process along with the accuracy of the result:

// multiply the result of microtime(true) by 1000
$milliseconds = microtime(true) * 1000;
echo $milliseconds;
// output: 1642423688198.1
?>

Use PHP microtime To Get Unix Timestamp in Microseconds

Is it possible to get the current Unix timestamp in microseconds? Undeniably, you can perform the necessary conversion to get time in microseconds, but the issue is the large value. As a microsecond is 1/1000000th part of a second, the resulting time value in microseconds will be long enough. And unfortunately, if you are using a 32-bit Operating System, you won’t get the desired time value.

Читайте также:  Где лучше программировать на python

However, if you have a 64-bit Operating System, you can multiply the output of the microtime(true) function by 1000000 to get the current time in microseconds.

– Coding Example

For instance, you have created a program that calls two functions with a timing difference of five seconds. Now, you want to see how many microseconds have elapsed between the two function calls. You’ll need to use the microtime(true) function and multiply the output of the same function by 1000000 at the time of calling the first function. Next, you’ll repeat the same process while executing the second function.

In the end, you’ll minus the second recorded time from the first one to get the elapsed time in microseconds as seen in the code fragment below:

// getting a part of a string
$part = substr(“Welcome To Timing Functions”,5);
// getting the time in microseconds
$first = microtime(true) * 1000000;
// setting the sleeping time to five seconds
sleep(5);
// replacing the word ‘Timing’ with ‘PHP’ in the substring
str_replace(“Timing”,”PHP”,$part);
// getting the time in microseconds
$second = microtime(true) * 1000000;
// calculating the time elapsed between the two function calls
$difference = $second – $first;
// printing a statement with elapsed microseconds
echo “The word ‘Timing’ was replaced after $difference microseconds of getting the substring.”;
?>

You will get the output that will look similar to this:

The word ‘Timing’ was replaced after 5015866 microseconds of getting the substring.

Format the Output

Can you format the PHP microtime result in such a way that the “microseconds as seconds” follow the “seconds” without a dot and a space? Although there isn’t any special function to provide the time in the mentioned format, you can use the preg_replace() function to format the output generated by the microtime in PHP.

– Coding Example

Suppose you have a time requirement in your program that expects the same time value as the one produced by the PHP microtime function, but you aren’t allowed to add a dot and a space. You’ll need to use the preg_replace() function by passing “/(0).(d+) (d+)/” pattern and a replacement string “$3$1$2” along with the output of the PHP microtime function.

Also, please look at the code shown here to implement the above example:

// using the microtime() function
$msec_sec = microtime();
// printing the time in “msec sec” format
echo “$msec_sec
”;
// using the preg_replace() function
echo preg_replace(‘/(0).(d+) (d+)/’, ‘$3$1$2’, $msec_sec);
?>

You will get a result similar to this after executing the above code:

0.18196800 1642435234
1642435234018196800

PHP Timing Functions Returning Time in Seconds Only

Unquestionably, the PHP microtime function gives quite satisfying results. But if you are concerned only about the current time in seconds, then the time() function can also be a good choice. The stated function returns the current time in seconds without considering the microseconds.

You can use it like this: time() .

– Coding Example

Imagine that you want to see how many seconds have passed since the Unix Epoch “January 1 1970 00:00:00 GMT.” Moreover, you want to compare the results of the microtime(true) and time() functions. So, there wouldn’t be a better idea than calling both of the functions at the same time to observe the difference in the obtained results.

Читайте также:  Считывание файла java bufferedreader

You can copy and paste the given code snippet to get your current time in seconds by using the microtime(true) and time() functions:

// using the time function
echo “Result of the time() function:” . time();
// using the microtime function
echo “Result of the microtime(true) function:” . microtime(true);
?>

Until you try out the above code, you can notice the difference in the outputs here:

Result of the time() function:1642432244
Result of the microtime(true) function:1642432244.2976

Conclusion

Summarizing the article, you have mastered the use of the PHP microtime function along with using the output of the same to generate different results. Now, it’s time to go through all the significant details to ensure that you don’t end up mixing any concepts:

  • The PHP microtime function returns the current Unix timestamp in “microseconds_as_seconds seconds” format.
  • The microtime(true) can be used to get the current Unix timestamp in seconds.
  • You can increase the number of digits returned by the microtime(true) by increasing the value of the precision directive.
  • You can multiply the output of the microtime(true) by 1000 to get the current time in milliseconds.
  • You can get the current time in microseconds by multiplying the result of the microtime(true) by 1000000.

Use of the php microtime function

No doubt, different PHP programs have different timing requirements. But the tasks won’t be difficult to handle when you have already gained clarity with the relevant concepts.

Источник

microtime

Функция microtime() возвращает текущую метку времени Unix с микросекундами. Эта функция доступна только на операционных системах, в которых есть системный вызов gettimeofday().

Список параметров

Если указано и установлено в TRUE , microtime() возвратит float вместо string , как описано в разделе возвращаемых значений ниже.

Возвращаемые значения

По умолчанию microtime() возвращает string в формате «msec sec», где sec представляет собой количество секунд с начала Эпохи Unix (1 января 1970 0:00:00 GMT), а msec — это количество микросекунд, прошедших после sec.

Если параметр get_as_float установлен в TRUE , то microtime() возвратит результат в вещественном виде ( float ), представляющий собой текущее время в секундах, прошедших с начала Эпохи Unix с точностью до микросекунд.

Примеры

Пример #1 Замер времени выполнения скрипта с помощью функции microtime()

/**
* Простая функция для реализации поведения из PHP 5
*/
function microtime_float ()
list( $usec , $sec ) = explode ( » » , microtime ());
return ((float) $usec + (float) $sec );
>

// Спим некоторое время
usleep ( 100 );

$time_end = microtime_float ();
$time = $time_end — $time_start ;

echo «Ничего не делал $time секунд\n» ;
?>

Пример #2 Замер времени выполнения скрипта в PHP 5

// Спим некоторое время
usleep ( 100 );

$time_end = microtime ( true );
$time = $time_end — $time_start ;

echo «Ничего не делал $time секунд\n» ;
?>

Пример #3 Пример использования microtime() и REQUEST_TIME_FLOAT (начиная с PHP 5.4.0)

// Выбираем время сна случайным образом
usleep ( mt_rand ( 100 , 10000 ));

// Начиная с PHP 5.4.0 в суперглобальном массиве $_SERVER доступно значение REQUEST_TIME_FLOAT.
// Оно содержит временную метку начала запроса с точностью до микросекунд.
$time = microtime ( true ) — $_SERVER [ «REQUEST_TIME_FLOAT» ];

echo «Ничего не делал $time секунд\n» ;
?>

Смотрите также

Источник

Оцените статью