Php работа с таймером

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

reetp/PHP-Timer

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This is a simple class for adding a timer to your PHP script.

This is NOT my code. I originally found it at codeaid.net but that site has since disappeared so I decided to preserve it.

I dug the following out of the Wayback machine archive here:

Sometimes when writing PHP code that is supposed to run fast we use the script execution calculation functions. Usually it involves (at least for me 🙂 copying the code from example #1 on PHP’s microtime function page and pasting it into your script only to do the same all over again the next time.

However, as good as that script is, it is not versatile enough. It does not, for example, allow you to time execution of only some lines or even more — some separated lines.

What if we needed to time the execution of fy()? It’s not impossible to do using the usual measures however it becomes a bit tedious. We would have to have multiple microtime calls, some local variable to store the total time and so on.

Therefore, to make my and hopefully someone else’s life easier, I wrote a class for those occasions. It allows you to start, stop, pause and resume timing of specific parts of your code. It would even allow you to calculate total time it takes to run fx() AND fz() together.

Here is the full source code of the class:

First, let’s look at the public methods that are available to you:

  • start() — start/resume the timer
  • stop() — stop/pause the timer
  • reset() — reset the timer
  • get([$format]) — stops the timer (if required) and returns the amount of time as number of seconds, milliseconds or microseconds.

The type of the result depends on the value of the $format parameter. The format can be one of the following three:

If the format is defined as seconds, the result will be a float, otherwise an int.

The class has a «queue» of times.

One Timer::start()/Timer::stop() cycle counts as one entry in the queue with its own execution time.

Therefore if you only do start() and stop() once, one queue item will be added.

If you call Timer::start() and Timer::stop() multiple times without calling Timer::reset() then multiple entries will get added to the queue.

Then, when you call Timer::get() the function will go through every queue entry, calculate the time that it took to execute and sum everything up to get the total time.

Whenever you need to restart the calculation just call Timer::reset(). That will clear the queue of current times.

The first and the most usual scenario, where you want to calculate the time it takes to run your whole script, is the easiest one.

Just add Timer::start() at beginning of the file/script and print Timer::get() at the end.

Next, let’s rewrite the examples we mentioned earlier. As you will see it is not much more different than timing the whole script:

for ($i = 0; $i < 100; $i++) < fx(); // calculate the time it takes to run fy() Timer::start(); fy(); Timer::stop(); fz(); >print Timer::get(); // or print Timer::get(Timer::MICROSECONDS); // or print Timer::get(Timer::MILLISECONDS); 

As previously mentioned, if you wanted to calculate the total time it takes to execute fx() AND fz() we would need to adjust the code to wrap two blocks of code instead of just one:

for ($i = 0; $i < 100; $i++) < // calculate the time it takes to run fx() Timer::start(); fx(); Timer::stop(); fy(); // calculate the time it takes to run fz() Timer::start(); fz(); Timer::stop(); >print Timer::get(); 

In case you want to track how much time it has taken for the script to run «up to now» you can simply call the Timer::get() function in the middle of the loop:

Timer::get() also stops the timer as it needs to set the final queue entry’s end time.

Therefore, if you call it between two blocks of code where the time gets calculated, you need to make sure you resume the timer by calling Timer::start().

Non-static version of the class

For those that don’t like static classes or who might need multiple instances of the Timer class, here is a modified version of the static class:

The way you would use this class is pretty similar to the static class except you can instantiate it and have multiple timers running on your page:

// instantiate two copies of the Timer class $t1 = new Timer(); $t2 = new Timer(); for ($i = 0; $i < 100; $i++) < // calculate the time it takes to run fx() using timer #1 $t1->start(); fx(); $t1->stop(); // calculate the time it takes to run fy() using timer #2 $t2->start(); fy(); $t2->stop(); > // get results print $t1->get(); print $t2->get(Timer::MILLISECONDS); 
 Timer::stop(); var_dump(Timer::get(Timer::MILLISECONDS)); // int(728) var_dump(Timer::get(Timer::MICROSECONDS)); // int(728340) var_dump(Timer::get(Timer::SECONDS)); // float(0.72834) ?> 

Hopefully these examples help. If not, please leave your comments with your questions or suggestions.

Regarding crashing — I suppose you are not seeing any error messages. In that case make sure you have

 ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); 

Try adding this function to the non-static version (this has been done):

/* * Get the average time of execution from all queue entries * * @return float */ public function getAverage($format = self::SECONDS) < $count = count($this->_queue); $sec = 0; $usec = $this->get(self::MICROSECONDS); if ($usec > self::USECDIV) < // move the full second microseconds to the seconds' part $sec += (int) floor($usec / self::USECDIV); // keep only the microseconds that are over the self::USECDIV $usec = $usec % self::USECDIV; >switch ($format) < case self::MICROSECONDS: $value = ($sec * self::USECDIV) + $usec; return round($value / $count, 2); case self::MILLISECONDS: $value = ($sec * 1000) + (int) round($usec / 1000, 0); return round($value / $count, 2); case self::SECONDS: default: $value = (float) $sec + (float) ($usec / self::USECDIV); return round($value / $count, 2); >> 

About

Источник

Класс EvTimer

Наблюдатели EvTimer — это обычные относительные таймеры, которые создают событие через заданное время и, опционально, периодически повторяют его через заданные интервалы времени.

Таймеры базируются на реальном времени, то есть если задать таймер с повторами раз в час и сбросить системные часы на Январь прошлого года, то таймер будет все также срабатывать через (грубо) час. «Грубо» потому, что отследить скачки времени достаточно сложно и некоторые неточности неизбежны.

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

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

Обзор классов

public __construct (
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)

final public static createStopped (
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvTimer

Свойства

Если равно 0.0 , то таймер автоматически остановится, когда будет превышено время ожидания. Если больше нуля, то таймер автоматически перейдёт в режим бесконечного повторения через заданные интервалы, пока вы его самостоятельно не остановите.

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

То есть, после того, как создан экземпляр EvTimer с after равным 5.0 и repeat равным 7.0 , remaining вернёт 5.0 . Когда таймер запустится и пройдёт 1 секунда, remaining вернёт 4.0 . когда таймер истечёт и будет перезапущен, будет «грубо» возвращено 7.0 (обычно чуть меньше, так как запуск callback-функции занимает время) и т.д.

Источник

Объективный таймер обратного отсчёта на PHP

Недавно мы разобрались с тем, как можно показывать новые данные на странице без перезагрузки, а до этого — как использовать PHP-скрипты. Сегодня объединим это в один проект и сделаем таймер обратного отсчёта на PHP.

В чём идея

Допустим, у нас есть какое-то событие, которое заканчивается 16 октября 2022 года в 14:00 — например распродажа. Нам нужно вывести таймер на страницу, который будет отсчитывать время до этого события.

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

Получается, что алгоритм будет работать так:

  • берём дату с сервера;
  • берём время с сервера;
  • находим разницу с искомой датой (16 октября 2022) и показываем, сколько времени осталось до наступления события;
  • если дата уже прошла, сообщаем об этом (отложим на другую итерацию, потому что событие только через год).

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

Что понадобится

Единственное, что нам нужно от сервера, — чтобы он мог выполнять PHP-скрипты. Это умеет делать практически любой веб-сервер в интернете, поэтому, если у вас есть хостинг и на хостинге можно размещать сайты, — скрипт тоже будет там работать.

Если хостинга с сайтом нет, то можно сделать так: установить MAMP и получить рабочий сервер с PHP у себя на компьютере.

Добавляем на странице место для таймера

Так как всю работу будут делать скрипты, то нам нужно просто указать место на странице, куда отправить результат. Возьмём наш учебный сайт mihailmaximov.ru и перед разделом с контактами добавим блок для таймера:

Этого будет достаточно, чтобы скрипт показал таймер в выбранном месте.

Пишем скрипт на странице

Первым делом подключаем jQuery — это позволит нам работать с AJAX-скриптом и вызывать его самым простым способом.

Теперь в раздел добавляем простой скрипт на JavaScript. Его задача — периодически обращаться к серверу и обновлять данные на странице. Благодаря AJAX он сможет это делать без перезагрузки, работая с отдельным блоком:

  

Готовим PHP-скрипт

Мы уже работали с PHP-скриптами, когда делали форму обратной связи, и там же рассказывали, как загрузить этот скрипт на сервер. Если пропустили этот цикл — будет полезно:

Источник

Читайте также:  Php static called class
Оцените статью