× 警告!旧版文档已经暂停维护,请查看新版文档。点击前往新版文档

协程内存开销

新版本4.0使用了C栈+PHP栈的协程实现方案。Server程序每次请求的事件回调函数中会创建一个新协程,处理完成后协程退出。

在协程创建时需要创建一个全新的内存段作为CPHP的栈,底层默认分配2M(C)虚拟内存+8K(PHP)内存(PHP-7.2或更高版本)。这里的虚拟内存是指操作系统并不会立即分配2M物理内存,系统会根据在内存实际读写时发生缺页中断,再分配实际内存。

由于PHP-7.1/7.0未提供设置栈内存尺寸的接口,这些版本每个协程将申请256KPHP内存

相比于异步回调程序,协程会增加一些内存管理的开销。有一定性能损耗。经过压测QPS依然可以达到较高的水平。

ab -c 100 -n 500000 -k http://127.0.0.1:9501/
This is ApacheBench, Version 2.3 <$Revision: 1706008 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 50000 requests
Completed 100000 requests
Completed 150000 requests
Completed 200000 requests
Completed 250000 requests
Completed 300000 requests
Completed 350000 requests
Completed 400000 requests
Completed 450000 requests
Completed 500000 requests
Finished 500000 requests


Server Software:        swoole-http-server
Server Hostname:        127.0.0.1
Server Port:            9501

Document Path:          /
Document Length:        24 bytes

Concurrency Level:      100
Time taken for tests:   3.528 seconds
Complete requests:      500000
Failed requests:        0
Keep-Alive requests:    500000
Total transferred:      132500000 bytes
HTML transferred:       12000000 bytes
Requests per second:    141738.54 [#/sec] (mean)
Time per request:       0.706 [ms] (mean)
Time per request:       0.007 [ms] (mean, across all concurrent requests)
Transfer rate:          36680.38 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       2
Processing:     0    1   0.9      0       7
Waiting:        0    1   0.9      0       7
Total:          0    1   0.9      0       7
WARNING: The median and mean for the processing time are not within a normal deviation
        These results are probably not that reliable.
WARNING: The median and mean for the waiting time are not within a normal deviation
        These results are probably not that reliable.
WARNING: The median and mean for the total time are not within a normal deviation
        These results are probably not that reliable.

Percentage of the requests served within a certain time (ms)
  50%      0
  66%      0
  75%      2
  80%      2
  90%      2
  95%      3
  98%      3
  99%      3
 100%      7 (longest request)