压力测试

压测脚本中创建了一个 PyDict ,分别读写 PHP 代码和 Python 代码执行 1000万次

  • PHP 版本PHP 8.2.3 (cli) (built: Mar 17 2023 15:06:57) (NTS)
  • Python 版本Python 3.11.5
  • 操作系统:Ubuntu 20.04
  • GCC 版本gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.2)

请注意此测试需要构造一个 1000 万元素的 HashTable,需要至少 2G 以上内存空间才可以运行

PHP

  1. <?php
  2. $dict = new PyDict();
  3. const COUNT = 10000000;
  4. $n = COUNT;
  5. $s = microtime(true);
  6. while ($n--) {
  7. $dict['key-' . $n] = $n * 3;
  8. }
  9. echo 'dict set: ' . round(microtime(true) - $s, 6) . ' seconds' . PHP_EOL;
  10. $c = 0;
  11. $n = COUNT;
  12. $s = microtime(true);
  13. while ($n--) {
  14. $c += $dict['key-' . $n];
  15. }
  16. echo 'dict get: ' . round(microtime(true) - $s, 6) . ' seconds' . PHP_EOL;

Python

  1. import time
  2. my_dict = {}
  3. COUNT = 10000000
  4. n = COUNT
  5. start_time = time.time()
  6. for i in range(n):
  7. my_dict["key-" + str(i)] = i * 3
  8. elapsed_time = time.time() - start_time
  9. print(f"dict set: {elapsed_time:.6f} seconds")
  10. n = COUNT
  11. total = 0
  12. start_time_get = time.time()
  13. for i in range(n):
  14. total += my_dict["key-" + str(i)]
  15. elapsed_time_get = time.time() - start_time_get
  16. print(f"dict get: {elapsed_time_get:.6f} seconds")

PHP 数组

  1. <?php
  2. ini_set('memory_limit', '2G');
  3. $dict = [];
  4. const COUNT = 10000000;
  5. $n = COUNT;
  6. $s = microtime(true);
  7. while ($n--) {
  8. $dict['key-' . $n] = $n * 3;
  9. }
  10. echo 'array set: ' . round(microtime(true) - $s, 6) . ' seconds' . PHP_EOL;
  11. $c = 0;
  12. $n = COUNT;
  13. $s = microtime(true);
  14. while ($n--) {
  15. $c += $dict['key-' . $n];
  16. }
  17. echo 'array get: ' . round(microtime(true) - $s, 6) . ' seconds' . PHP_EOL;

结果对比

  1. (base) htf@swoole-12:~/workspace/python-php/docs/benchmark$ php dict.php
  2. dict set: 4.663758 seconds
  3. dict get: 3.980076 seconds
  4. (base) htf@swoole-12:~/workspace/python-php/docs/benchmark$ php array.php
  5. array set: 1.578963 seconds
  6. array get: 0.831129 seconds
  7. (base) htf@swoole-12:~/workspace/python-php/docs/benchmark$ python dict.py
  8. dict set: 5.321664 seconds
  9. dict get: 4.969081 seconds
  10. (base) htf@swoole-12:~/workspace/python-php/docs/benchmark$

Python 测试为基准:

脚本名称 Set Get
dict.php 114% 125%
array.php 337% 599%
  • phpyPHP 代码写入 PyDict 的性能比原生 Python14%,读取性能高 25%
  • PHP 写入 PHP Array 的性能比 Python 写入 Dict237%,读取高出了近 500%