今天小编给大家分享一下GoFrame基于性能怎么测试grpool使用场景的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
grpool相比于goroutine更节省内存,但是耗时更长;
原因也很简单:grpool复用了协程,减少了协程的创建和销毁,减少了内存消耗;也因为协程的复用,总的goroutine数量更少,导致耗时更多。
开启for循环,开启一万个协程,分别使用原生goroutine和grpool执行。
看两者在内存占用和耗时方面的差别。
package main
import (
"flag"
"fmt"
"github.com/gogf/gf/os/grpool"
"github.com/gogf/gf/os/gtime"
"log"
"os"
"runtime"
"runtime/pprof"
"sync"
"time"
)
func main() {
//接收命令行参数
flag.Parse()
//cpu分析
cpuProfile()
//主逻辑
//demoGrpool()
demoGoroutine()
//内存分析
memProfile()
}
func demoGrpool() {
start := gtime.TimestampMilli()
wg := sync.WaitGroup{}
for i := 0; i < 10000; i++ {
wg.Add(1)
_ = grpool.Add(func() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("运行中占用内存:%d Kb\n", m.Alloc/1024)
time.Sleep(time.Millisecond)
wg.Done()
})
fmt.Printf("运行的协程:", grpool.Size())
}
wg.Wait()
fmt.Printf("运行的时间:%v ms \n", gtime.TimestampMilli()-start)
select {}
}
func demoGoroutine() {
//start := gtime.TimestampMilli()
wg := sync.WaitGroup{}
for i := 0; i < 10000; i++ {
wg.Add(1)
go func() {
//var m runtime.MemStats
//runtime.ReadMemStats(&m)
//fmt.Printf("运行中占用内存:%d Kb\n", m.Alloc/1024)
time.Sleep(time.Millisecond)
wg.Done()
}()
}
wg.Wait()
//fmt.Printf("运行的时间:%v ms \n", gtime.TimestampMilli()-start)
}
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile `file`")
var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
func cpuProfile() {
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil { //监控cpu
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
}
func memProfile() {
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
runtime.GC() // GC,获取最新的数据信息
if err := pprof.WriteHeapProfile(f); err != nil { // 写入内存信息
log.Fatal("could not write memory profile: ", err)
}
f.Close()
}
}
组件 | 占用内存 | 耗时 |
---|---|---|
grpool | 2229 Kb | 1679 ms |
goroutine | 5835 Kb | 1258 ms |
以上就是“GoFrame基于性能怎么测试grpool使用场景”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。