php get time in milliseconds

microtime

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

microtime — Return current Unix timestamp with microseconds

Description

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

For performance measurements, using hrtime() is recommended.

Parameters

Return Values

By default, microtime() returns a string in the form «msec sec», where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also expressed in seconds.

Examples

Example #1 Timing script execution

// Sleep for a while
usleep ( 100 );

Example #2 microtime() and REQUEST_TIME_FLOAT

See Also

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 лет, измеренный в микросекундах.

Источник

Php get time in milliseconds

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

time — Return current Unix timestamp

Description

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Parameters

This function has no parameters.

Return Values

Returns the current timestamp.

Examples

Example #1 time() example

The above example will output something similar to:

Notes

See Also

User Contributed Notes 21 notes

The documentation should have this info. The function time() returns always timestamp that is timezone independent (=UTC).

Two quick approaches to getting the time elapsed in human readable form.

$nowtime = time ();
$oldtime = 1335939007 ;

/** Output:
time_elapsed_A: 6d 15h 48m 19s
time_elapsed_B: 6 days 15 hours 48 minutes and 19 seconds ago.
**/
?>

A time difference function that outputs the time passed in facebook’s style: 1 day ago, or 4 months ago. I took andrew dot macrobert at gmail dot com function and tweaked it a bit. On a strict enviroment it was throwing errors, plus I needed it to calculate the difference in time between a past date and a future date.

Argument order (begin date, end date) doesn’t matter.

I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.

Below, a function to create TNG-style stardates, taking 2009 to start stardate 41000.0. In fact, the offset is trivial to adjust if you wish to begin from a different date.

Here’s a snippet of code that demonstrates the difference:

// Find the next second
$nextSecond = time () + 1 ;

// TIME: 1525735820 uTIME: 1525735820.997716
// TIME: 1525735820 uTIME: 1525735820.998137
// TIME: 1525735820 uTIME: 1525735820.998528
// TIME: 1525735820 uTIME: 1525735820.998914
// TIME: 1525735820 uTIME: 1525735820.999287
// TIME: 1525735820 uTIME: 1525735820.999657
// TIME: 1525735820 uTIME: 1525735821.000026 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000367 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000705 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001042 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001379 time() is behind
// TIME: 1525735821 uTIME: 1525735821.001718
// TIME: 1525735821 uTIME: 1525735821.002070
// TIME: 1525735821 uTIME: 1525735821.002425
// TIME: 1525735821 uTIME: 1525735821.002770
// TIME: 1525735821 uTIME: 1525735821.003109
// TIME: 1525735821 uTIME: 1525735821.003448
// TIME: 1525735821 uTIME: 1525735821.003787
// TIME: 1525735821 uTIME: 1525735821.004125
// TIME: 1525735821 uTIME: 1525735821.004480

Here’s a little tweak for those having trouble with cookies being set in the future or past (even after setting the date.timezone directive in php.ini or using the function):

Does anyone know if the year 2038 issue will be solved in PHP?

Lets imagine it’s year 2039 and the time() function will return negative numbers? This is not acceptable.

Using the DateTime interface is nice, but will these timestamp helper functions be removed or fixed?

If you want to create a «rounded» time stamp, for example, to the nearest 15 minutes use this as a reference:

= 60 * 15 // 60 seconds per minute * 15 minutes equals 900 seconds
//$round_numerator = 60 * 60 or to the nearest hour
//$round_numerator = 60 * 60 * 24 or to the nearest day

//If it was 12:40 this would return the timestamp for 12:45;
//3:04, 3:00; etc.
?>

I built this function to get the strtotime numbers for the beginning and ending of the month and return them as arrays in an object. Cheers.

The issue are highlighting is with the date() function, not with time(). the following code demonstrates this:

A better way to get a nice time-format (1 year ago, 2 months until) without all the trailing months, days, hours, minutes, seconds in the result is by using the DateTime format and using the date_diff function as they both does most of the heavy lifting for you

Function below as example

// Ex. (time now = November 23 2017)
getTimeInterval ( «2016-05-04 12:00:00» ); // Returns: 1 year ago
getTimeInterval ( «2017-12-24 12:00:00» ); // Returns: 1 month until

I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.

Here’s one way to generate all intermediate dates (in mySQL format) between any 2 dates.
Get start and end dates from user input, you’d need to do the basic validations that :
— start and end dates are valid dates
— start date //start date 2001-02-23
$sm = 2 ;
$sd = 23 ;
$sy = 2001 ;

//end date 2001-03-14
$em = 3 ;
$ed = 14 ;
$ey = 2001 ;

A method return GMT time (gmttime):

elapsed time function with precision:

Here is a version for the difference code that displays «ago» code.

It does use some precision after the time difference is longer than a day. ( ie days are more than 60 * 60 * 24 hours long )

// Make the entered date into Unix timestamp from MySQL datetime field

// Calculate the difference in seconds betweeen
// the two timestamps

Источник

How to get current time in milliseconds in PHP?

November 2018

293k time

14 answers

Примечание: PHP5 требуется для этой функции из-за улучшения с микропорой () и также необходимы КАМИ математического модуля (как мы имеем дело с большими числами, вы можете проверить, если у вас есть модуль в phpinfo).

Надеюсь, что это поможет вам.

Примечание: PHP5 требуется для этой функции из-за улучшения с микропорой () и также необходимы КАМИ математического модуля (как мы имеем дело с большими числами, вы можете проверить, если у вас есть модуль в phpinfo).

Надеюсь, что это поможет вам.

Примечание: PHP5 требуется для этой функции из-за улучшения с микропорой () и также необходимы КАМИ математического модуля (как мы имеем дело с большими числами, вы можете проверить, если у вас есть модуль в phpinfo).

Надеюсь, что это поможет вам.

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

Это работает, даже если вы на 32-битной PHP:

Обратите внимание, это не дает вам целые числа, но строки. Однако это прекрасно работает во многих случаях, например, при создании URL-адреса для запросов REST.

Если вам нужно целые числа, 64-разрядный PHP является обязательным.

Затем вы можете использовать приведенный выше код и приведение к (INT):

Или вы можете использовать старые добрые Однострочники:

Вы можете использовать следующую функцию, чтобы сделать это:

Использование microtime(true) в PHP 5 или следующей модификации в PHP 4:

Портативный способ, чтобы написать этот код будет выглядеть так:

Примечание: PHP5 требуется для этой функции из-за улучшения с микропорой () и также необходимы КАМИ математического модуля (как мы имеем дело с большими числами, вы можете проверить, если у вас есть модуль в phpinfo).

Надеюсь, что это поможет вам.

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

64 бит платформы только!

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

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

Размер целого зависит от платформы, хотя максимальное значение около двух миллиардов обычного значения (это 32-битных знакового). 64-разрядные платформы, как правило, имеют максимальное значение около 9E18, для Windows, который всегда 32 бит, за исключением. PHP не поддерживает целые числа без знака. Целое размер может быть определен с использованием постоянного PHP_INT_SIZE, и максимальное значение, используя константу PHP_INT_MAX начиная с PHP 4.4.0 и PHP 5.0.5.

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

Второе число секунды (целое число) предшествует десятичной части.

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

Наконец, эта функция является немного более точным, чем

Это то же самое значение, возвращаемое echo PHP_INT_MAX / (1000000*3600*24*365);

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

Источник

How do I get the current Unix time in milliseconds in Bash?

How do I get the current Unix time in milliseconds (i.e number of milliseconds since Unix epoch January 1 1970)?

18 Answers 18

will return the number of seconds since the epoch.

returns the seconds and current nanoseconds.

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

You may simply use %3N to truncate the nanoseconds to the 3 most significant digits (which then are milliseconds):

This works e.g. on my Kubuntu 12.04 (Precise Pangolin).

But be aware that %N may not be implemented depending on your target system. E.g. tested on an embedded system (buildroot rootfs, compiled using a non-HF ARM cross toolchain) there was no %N :

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

date +%N doesn’t work on OS X, but you could use one of

My solution is not the best, but it worked for me:

I just needed to convert a date like 2012-05-05 to milliseconds.

Just throwing this out there, but I think the correct formula with the division would be:

This solution works on macOS.

If you consider using a Bash script and have Python available, you could use this code:

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

For the people that suggest running external programs to get the milliseconds. at that rate, you might as well do this:

Point being: before picking any answer from here, please keep in mind that not all programs will run under one whole second. Measure!

If you are looking for a way to display the length of time your script ran, the following will provide a (not completely accurate) result:

As near the beginning of your script as you can, enter the following

This’ll give you a starting value of something like 1361802943996000000.

At the end of your script, use the following

which will display something like

runtime: 12.383 seconds

(1*10^09) can be replaced with 1000000000 if you wish

«scale=3» is a rather rare setting that coerces bc to do what you want. There are lots more!

I only tested this on Windows 7/MinGW. I don’t have a proper *nix box at hand.

Источник

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

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