php microtime to date

Функции временных меток PHP

PHP предоставляет несколько функций для выполнения операций с временными данными. В этой статье мы рассмотрим функции временных меток PHP.

Временная метка — это значение, представленное в секундах, которое рассчитывается с начала эпохи UNIX, 1 января 1970 года.

В этой статье мы рассмотрим, как с помощью PHP-функций даты и времени, связанных с временными метками:

php microtime to date. Смотреть фото php microtime to date. Смотреть картинку php microtime to date. Картинка про php microtime to date. Фото php microtime to date

Получение текущей временной метки в PHP

Текущее значение временной метки можно получить тремя способами.

Это функция PHP для получения текущего значения временной метки. Она не принимает никаких аргументов. Пример использования:

StrToTime ()

Функция предназначена для получения метки времени из заданной строки, представляющей собой значение даты. Например, “Tuesday last week”, “+1 week”, “21 November 2008” и т. д.

Для получения текущей временной метки нужно передать функции значение “now”:

При вызове strtotime() с переданными некорректными данными, которые не поддерживаются PHP, а функция вернет значение false.

mktime()

Используется для получения метки времени UNIX. Функция принимает набор параметров, обозначающих час, минуты, секунды, месяц, день и год. А также дополнительный флаг, представляющий состояние летнего времени.

Чтобы получить текущую временную метку, в качестве параметра функции передается date() с соответствующими значениями. Например:

microtime()

Описанные выше функции PHP возвращают только десятизначное значение. Но microtime() возвращает количество секунд и микросекунд, прошедших с начала эпохи UNIX.

Преобразование даты и времени в метку

Функции strtotime() и mktime() также используются для преобразования указанной даты в формат временной метки.

Функции strtotime() нужно передать дату в любом из поддерживаемых PHP форматов. Например, dd / mm / yyyy, mm / dd / yyyy и т. д. Чтобы использовать mktime(), нужно разложить дату и отправить ее компоненты в эту функцию.

Также можно преобразовать значение метки времени в дату, используя функцию date(). Для этого необходимо передать требуемый формат даты в качестве первого параметра и временную метку в качестве второго. Например:

Скачать исходный код

Пожалуйста, оставьте свои мнения по текущей теме статьи. За комментарии, дизлайки, подписки, лайки, отклики низкий вам поклон!

Источник

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:

Источник

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
//функция для конвертации времени, принимает значения в секундах

Источник

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 microtime to date. Смотреть фото php microtime to date. Смотреть картинку php microtime to date. Картинка про php microtime to date. Фото php microtime to date

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.

Источник

Определяем время работы скрипта PHP

php microtime to date. Смотреть фото php microtime to date. Смотреть картинку php microtime to date. Картинка про php microtime to date. Фото php microtime to dateДоброго времени суток, коллеги! 🙂

Сегодня я решил затронуть такую тему, как время выполнения скрипта PHP и его определение.

Не скажу, что данная необходимость возникает каждый день, но время от времени на практике возникают ситуации, когда нужно получить время работы скрипта PHP.

Особенно часто за таким занятием можно застукать разработчиков, занимающихся рефакторингом кода и оптимизацией существующих алгоритмов, когда время выполнения PHP скрипта является ключевым фактором при выборе конечного варианта.

Ну, и ещё иногда данные цифры требуют менеджеры и заказчики, желающие выяснить, сколько времени потребуется на то или иное действие в коде.

Поэтому я и решил написать данную коротенькую заметку, в которой решил изложить порядок действий в аналогичной ситуации.

Сперва мы рассмотрим сам алгоритм определения времени исполнения PHP скрипта, а затем я приведу код, с помощью которого он будет реализовываться.

Время выполнения PHP скрипта — алгоритм определения

Порядок наших действий будет предельно прост:

Полученное в итоге значение как раз и будет временем выполнения PHP скрипта, которое можно будет принимать во внимание при дальнейшей оптимизации и прочих действиях.

Время работы PHP скрипта — реализация алгоритма

Для вывода текущего времени в PHP коде я решил воспользоваться стандартной PHP функцией microtime(), которая возвращает текущую метку времени в Unix формате с микросекундами.

Зачем такая точность?

Затем, чтобы уловить малейшие изменения времени выполнения скриптов, т.к. иногда доли секунды могут быть фатальны и привести к большим потерям при использовании медленного кода в больших масштабах.

php microtime to date. Смотреть фото php microtime to date. Смотреть картинку php microtime to date. Картинка про php microtime to date. Фото php microtime to date

Ну, и плюс, учёт микросекунд при вычислениях влияет на точность калькуляций в положительную сторону.

Для демонстрации своих теоретических повествований я написал простенький скриптик, который вычисляет время прогона пустого цикла с 30 000 000 итераций (решил взять побольше для наглядности):

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

Функция PHP microtime() имеет всего один параметр get_as_float, при указании которому значения true можно получить текущее время PHP в секундах, прошедших с начала эпохи Unix с точностью до микросекунд.

Поскольку мне нужно было именно текущее время, а не количество секунд с начала эпохи Unix, то я воспользовался данным параметром, что можно видеть в моём коде.

В итоге, с помощью функции echo(), на экран вывелось следующее сообщение: Скрипт был выполнен за 1.3156361579895 секунд.

Чтобы определить, что данная методика работает верно, я решил задать фиксированное время выполнения скрипта с помощью функции sleep(), которая делает задержку выполнения скрипта на указанное количество секунд.

В итоге, следующая конструкция вернула сообщение Скрипт был выполнен за 2.0000510215759 секунд:

Превышение указанной задержки на микроскопические доли секунд можно списать на время вызова кодовых конструкций и обработку результатов их выполнения серверным железом, поэтому на них вполне можно закрыть глаза.

Если они будут всё-таки раздражать вас или вашего заказчика, то можете воспользоваться хаком в виде банального округления до сотых или тысячных долей с помощью PHP функции round(), задействовав её следующим образом:

Результатом выполнения данного куска кода для вышеприведённого примера станет значение в кругленькие 2 секунды, что устроит самых искушённых перфекционистов 🙂

На этом сегодняшняя информация о том, как можно определить время выполнения скрипта PHP, подходит к концу.

php microtime to date. Смотреть фото php microtime to date. Смотреть картинку php microtime to date. Картинка про php microtime to date. Фото php microtime to date

Пишите свои отзывы в комментариях и задавайте интересующие вас вопросы в пабликах проекта в социальных сетях.

Всем удачи и до новых встреч! 🙂

P.S.: если вам нужен сайт либо необходимо внести правки на существующий, но для этого нет времени и желания, могу предложить свои услуги.

Более 5 лет опыта профессиональной разработки сайтов. Работа с PHP, OpenCart, WordPress, Laravel, Yii, MySQL, PostgreSQL, JavaScript, React, Angular и другими технологиями web-разработки.

Опыт разработки проектов различного уровня: лендинги, корпоративные сайты, Интернет-магазины, CRM, порталы. В том числе поддержка и разработка HighLoad проектов. Присылайте ваши заявки на email cccpblogcom@gmail.com.

И с друзьями не забудьте поделиться 😉

Источник

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

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