3v4l.org

run code in 300+ PHP versions simultaneously
<?php // Dont' abuse 3v4l $n = 10000; // 空循环时间 $start = microtime(true); for ($i = 0; $i < $n; $i++) { } $finish = microtime(true); $loop_time = $finish - $start; // 普通 $start = microtime(true); for ($i = 0; $i < $n; $i++) { $t = time(); } $finish = microtime(true); $microtime_time = $finish - $start - $loop_time; echo "microtime: $microtime_time \t100%" . PHP_EOL; // 方式一:通过 PHP 实现,时间缓存在静态变量中 class CacheTime { private static $time = 0; public static function getTime() { return self::$time; } // 需要 timer 定时调用 setTime 更新 public static function setTime() { self::$time = microtime(true); } } $start = microtime(true); for ($i = 0; $i < $n; $i++) { $t = CacheTime::getTime(); } $finish = microtime(true); $class_cache_time = $finish - $start - $loop_time; echo "CacheTime: $class_cache_time \t" . ($class_cache_time / $microtime_time * 100) . '%' . PHP_EOL;; // 方式二:通过扩展实现,时间存在 C 的静态/全局变量中,通过定时器更新 $start = microtime(true); for ($i = 0; $i < $n; $i++) { // gc_enabled 直接取 GC_G(gc_enabled),没有参数,接近时间缓存的实现 $t = gc_enabled(); } $finish = microtime(true); $c_cache_time = $finish - $start - $loop_time; echo "cache_time: $c_cache_time \t" . ($c_cache_time / $microtime_time * 100) . '%' . PHP_EOL;

preferences:
32.54 ms | 406 KiB | 5 Q