Sunday, September 23, 2007

currentTimeMillis() in PHP

Tonight I really wished I had the PHP equivalent of Java's System.getCurrentTimeMillis() or JavaScript's getTime(). I didn't have one, so I whipped one up using microtime. Here it is:

// return our current unix time in millis
function current_millis() {
    list($usec, $sec) = explode(" ", microtime());
    return round(((float)$usec + (float)$sec) * 1000);
}

Here's the classic usage:

  $started = current_millis();
  someQuestiontionableOperation();
  echo "We took: " . (current_millis() - $started) . " millis to run";

Enjoy!

4 comments:

  1. Thanks, really useful.

    ReplyDelete
  2. Charlie -

    Glad you found this useful.

    This is actually fairly dated. You should able to just say:


    $start = microtime(true);
    someCode();
    $end = microtime(true);
    echo "It took: " . round($end - $start, 3) . "secs";

    ReplyDelete
  3. Anonymous2:25 AM

    Thanks a lot, I needed this to translate a piece of Java code to PHP.

    ReplyDelete