php time with milliseconds

How to subtract microtime and display date with milliseconds in php?

For example: I have set end date and time

then I have current date or start date with converted from microtime

I want my output to be like this: 00:00:02.452

2 Answers 2

You need to use microtime for the start/end values, and only format it for display at the end.

Note: this is returning float values from microtime and using float arithmetic to simplify the math, so your numbers may be extremely slightly off due to the float rounding problem, but you are rounding the result to 3 digits in the end anyway, and minor fluctuations in processor timing are greater than floating point errors anyway, so this is not problem for you on multiple levels.

Well phpmyadmin uses this a code like this to calculate the time that a query took. It’s similar to your requirements:

I think this should work for you. You just have to figure your output format

php time with milliseconds. Смотреть фото php time with milliseconds. Смотреть картинку php time with milliseconds. Картинка про php time with milliseconds. Фото php time with milliseconds

Not the answer you’re looking for? Browse other questions tagged php microtime or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

DateTime with microseconds

In my code, I’m using DateTime objects to manipulate dates, then convert them to timestamp in order to save them in some JSON files.

For some reasons, I want to have the same thing as DateTime (or something close), but with microseconds precision (that I would convert to float when inserting inside the JSON files).

The goal is to be able to manipulate microtimes with objects.

In the date() documentation, there is something that indicates that DateTime can be created with microseconds, but I wasn’t able to find how.

u Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

I have tried to set the timestamp of a DateTime object with a floating value ( microtime(true) ), but it doesn’t work (I think it converts the timestamp to an int, causing the loss of the microseconds).

Here is how i tried

EDIT : I saw this code, which allows to add microseconds to a DateTime, but I would need to apply a lot of modifications to the microtime before creating the DateTime. Since I will use this a lot, I want to do as little modifications to the microtime as possible before getting the «microtime object».

10 Answers 10

Here’s a very simple method of creating a DateTime object that includes microtime.

I didn’t delve into this question too deeply so if I missed something I apologize but hope you find this helpful.

I tested it out and tried various other ways to make this work that seemed logical but this was the sole method that worked for PHP versions prior to 7.1.

However there was a problem, it was returning the correct time portion but not the correct day portion (because of UTC time most likely) Here’s what I did (still seems simpler IMHO):

UPDATE
As pointed out in comments, as of PHP 7.1, the method recommended by Planplan appears to be superior to the one shown above.

So, again for PHP 7.1 and later it may be better to use the below code instead of the above:

Please be aware that the above works only for PHP versions 7.1 and above. Previous versions of PHP will return 0s in place of the microtime, therefore losing all microtime data.

NOTE: in testing the above sandbox I did not ever see the microtime(TRUE) failure which Planplan mentioned that he experienced. The updated method does, however, appear to record a higher level of precision as suggested by KristopherWindsor.

NOTE2: Please be aware that there may be rare cases where either approach will fail because of an underlying decision made regarding the handling of microseconds in PHP DateTime code. Either:

Источник

How to get current time in milliseconds in PHP?

15 Answers 15

The short answer is:

90%: substr(microtime(true) * 1000, 0, 13);

There is also gettimeofday that returns the microseconds part as an integer.

Short answer:

64 bits platforms only!

[ If you are running 64 bits PHP then the constant PHP_INT_SIZE equals to 8 ]

Long answer:

If you want an equilvalent function of time() in milliseconds first you have to consider that as time() returns the number of seconds elapsed since the «epoch time» (01/01/1970), the number of milliseconds since the «epoch time» is a big number and doesn’t fit into a 32 bits integer.

The size of an integer in PHP can be 32 or 64 bits depending on platform.

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that’s 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

If you have 64 bits integers then you may use the following function:

microtime() returns the number of seconds since the «epoch time» with precision up to microseconds with two numbers separated by space, like.

The second number is the seconds (integer) while the first one is the decimal part.

The above function milliseconds() takes the integer part multiplied by 1000

then adds the decimal part multiplied by 1000 and rounded to 0 decimals

Finally, that function is slightly more precise than

that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result. This is due to the limited precision of the float type ( microtime(true) returns a float). Anyway if you still prefer the shorter round(microtime(true)*1000); I would suggest casting to int the result.

Even if it’s beyond the scope of the question it’s worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microseconds without incurring in overflow.

That’s the same value you get with

In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.

Источник

microtime

(PHP 4, PHP 5, PHP 7, PHP 8)

microtime — Возвращает текущую метку времени Unix с микросекундами

Описание

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

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

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

Примеры

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

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

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

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

User Contributed Notes 20 notes

All these timing scripts rely on microtime which relies on gettimebyday(2)

This can be inaccurate on servers that run ntp to syncronise the servers
time.

For timing, you should really use clock_gettime(2) with the
CLOCK_MONOTONIC flag set.

This returns REAL WORLD time, not affected by intentional clock drift.

This may seem a bit picky, but I recently saw a server that’s clock was an
hour out, and they’d set it to ‘drift’ to the correct time (clock is speeded
up until it reaches the correct time)

Those sorts of things can make a real impact.

Any solutions, seeing as php doesn’t have a hook into clock_gettime?

Here is a solution to easily calculate the execution time of a script without having to alter any configuration parameter. It uses the former way of getting microseconds.

It is important to note that microtime(TRUE) does NOT always return a float (at least in PHP 5.x; I have not tested 7.x). If it happens to land on an exact second, it returns an integer instead.

The description of «msec», in this documentation, is very bad.

It is NOT the microseconds that have elapsed since «sec» (if so, it should be given as an integer, without the «0.» in the beginning of the string).
It IS the fractional part of the time elapsed since «sec», with microseconds (10E-6) precision, if the last «00» are not considered significant».
If the last two digits are significant, then we would have a precision of 10E-8 seconds.

mixed mini_bench_to(array timelist[, return_array=false])
return a mini bench result

-the timelist first key must be ‘start’
-default return a resume string, or array if return_array= true :
‘total_time’ (ms) in first row
details (purcent) in next row

The function to include :

Using microtime() to set ‘nonce’ value:

Out of the box, microtime(true) will echo something like:

Which is obviously less than microsecond accuracy. You’ll probably want to bump the ‘precision’ setting up to 16 which will echo something like:

*Internally* it will be accurate to the six digits even with the default ‘precision’, but a lot of things (ie. NoSQL databases) are moving to all-text representations these days so it becomes a bit more important.

* 14 at the time of writing

//timestamp in milliseconds:
intval ( microtime ( true )* 1000 )

//timestamp in microseconds:
intval ( microtime ( true )* 1000 * 1000 )

//timestamp in nanoseconds:
intval ( microtime ( true )* 1000 * 1000 * 1000 )

While doing some experiments on using microtime()’s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows.

The solution was to instead use gettimeofday()’s output, as its usec value followed no quantifiable pattern on any of the three test platforms.

A convenient way to write the current time / microtime as formatted string in your timezone as expression?

DateTime now is: 2018-06-01 14:54:58 Europe/Berlin
Microtime now is: 180601 14:54:58.781716 Europe/Berlin

I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8

$time_start = micro_time ();
sleep ( 1 );
$time_stop = micro_time ();

I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.

?>

However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm)
If system time change, result of this function can be unpredictable (much greater or less than zero).

Of the methods I’ve seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime.

I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn’t a problem of other things putting a load spike on the server. I’ll admit I didn’t take into account martijn at vanderlee dot com’s comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary.

Get date time with milliseconds

Test accuracy by running it in a loop.

//Function to convert microtime return to human readable units
//функция для конвертации времени, принимает значения в секундах

Источник

Как узнать текущее время в миллисекундах в PHP?

Короткий ответ является:

Существует также, gettimeofday что возвращает часть микросекунд в виде целого числа.

Короткий ответ:

Только 64-битные платформы!

[ Если вы используете 64-битный PHP, то константа PHP_INT_SIZE равна 8 ]

Длинный ответ:

Размер целого числа в PHP может быть 32 или 64 бит в зависимости от платформы.

Если у вас 64-разрядные целые числа, вы можете использовать следующую функцию:

Вышеуказанная функция milliseconds() принимает целую часть, умноженную на 1000

затем добавляет десятичную часть, умноженную на 0 1000 и округленную до 0

Наконец, эта функция немного точнее, чем

что с соотношением 1:10 (прибл.) возвращает на 1 миллисекунду больше, чем правильный результат. Это связано с ограниченной точностью типа с плавающей точкой ( microtime(true) возвращает значение с плавающей точкой). В любом случае, если вы по-прежнему предпочитаете более короткое, round(microtime(true)*1000); я бы предложил int использовать результат.

Даже если это выходит за рамки вопроса, стоит упомянуть, что, если ваша платформа поддерживает 64-битные целые числа, вы также можете получить текущее время в микросекундах без переполнения.

Это то же значение, которое вы получаете с

Другими словами, 64-разрядное целое число со знаком может хранить промежуток времени более 200 000 лет, измеренный в микросекундах.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *