PHP 脚本花费的时间超出预期

问题描述 投票:0回答:1

我的 PHP 脚本需要 32 秒,而使用 Java 执行相同的操作需要约 2 毫秒,使用 golang 需要 200 毫秒。

为什么 PHP 脚本需要这么长时间?我知道 PHP 是一种解释性语言,它在解释器中执行的指令比我们看到的要多得多,但是这段代码是如此简单,还有其他原因吗?

环境信息:

php version: PHP 7.4.3-4ubuntu2.19 (cli), Zend Engine v3.4.0
hardware: 15G RAM, 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
software: ubuntu 20.04 LTS on Windows WSL2. 

php代码:

<?php
 
     function test(int $max, int $start) {
 
         $time_start = microtime(true);
         while ($start < $max) {
             $start = $start+1;
         }
 
         $time_end = microtime(true);
 
         //dividing with 60 will give the execution time in minutes otherwise seconds
         $execution_time = ($time_end - $time_start);
 
         //execution time of the script
         print('Total Execution Time: '.$execution_time.' Seconds \n');
     }
 
     test(1000000000, 0);

Java代码:

import java.time.Duration;
import java.time.Instant;
  
import java.util.ArrayList;
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadLocalRandom;
import javax.swing.*;
  
  
  class Benchmark {
 
      public static void main(String args[]) {
 
          int max = 1000000000;
          int index = 0;
 
          long start = System.currentTimeMillis();
 
          while(index < max) {
              index++;
          }
 
          long end = System.currentTimeMillis();
          System.out.println("Elapsed Time in millseconds: "+ (end-start));
          System.out.println("index: "+ index);
 
      }
  }
java php loops benchmarking
1个回答
0
投票

虽然我怀疑我们的系统在功能上相似,但我使用的是旧版(7.1)PHP,但我得到:

Total Execution Time: 9.6295697689056 Seconds

对于可进行 10 亿次操作的脚本语言来说,这似乎完全合理。我怀疑新版本的 PHP 速度更快。

所以我的回答更多的是一种解释,在不了解您的环境的情况下,我不确定您的问题是否有答案。

© www.soinside.com 2019 - 2024. All rights reserved.