Skip to content

Commit cac078b

Browse files
committed
perf: dashboard
1 parent 252374d commit cac078b

File tree

1 file changed

+52
-41
lines changed

1 file changed

+52
-41
lines changed

internal/service/dashboard/dashboard.go

Lines changed: 52 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
package dashboard
77

88
import (
9+
"errors"
10+
"golang.org/x/sync/errgroup"
911
"math/big"
1012
"os"
1113
"runtime"
@@ -22,48 +24,57 @@ import (
2224
v1 "github.com/ch3nnn/webstack-go/api/v1"
2325
)
2426

25-
func (s *service) memory() (m mem.VirtualMemoryStat) {
26-
info, err := mem.VirtualMemory()
27-
if err != nil {
28-
return m
29-
}
30-
31-
return *info
32-
}
33-
34-
func (s *service) disk() (d disk.UsageStat) {
35-
info, err := disk.Usage("/")
36-
if err != nil {
37-
return d
38-
}
39-
40-
return *info
41-
}
42-
43-
func (s *service) cpu() (c cpu.InfoStat) {
44-
info, err := cpu.Info()
45-
if err != nil {
46-
return c
47-
}
48-
49-
if len(info) > 0 {
50-
return info[0]
51-
}
52-
53-
return c
54-
}
55-
5627
func (s *service) Dashboard(ctx *gin.Context) (*v1.DashboardResp, error) {
57-
memoryInfo := s.memory()
58-
diskInfo := s.disk()
59-
cpuInfo := s.cpu()
60-
61-
dir, _ := os.Getwd()
62-
63-
var cpuPercent float64
64-
cpuPercents, _ := cpu.Percent(time.Second, false)
65-
if len(cpuPercents) > 0 {
66-
cpuPercent = mathutil.RoundToFloat(cpuPercents[0], 2)
28+
var (
29+
g errgroup.Group
30+
dir string
31+
cpuPercent float64
32+
memoryInfo *mem.VirtualMemoryStat
33+
diskInfo *disk.UsageStat
34+
cpuInfo *cpu.InfoStat
35+
)
36+
37+
g.Go(func() (err error) {
38+
memoryInfo, err = mem.VirtualMemoryWithContext(ctx)
39+
if err != nil {
40+
return err
41+
}
42+
return
43+
})
44+
g.Go(func() (err error) {
45+
diskInfo, err = disk.UsageWithContext(ctx, "/")
46+
if err != nil {
47+
return err
48+
}
49+
return
50+
})
51+
g.Go(func() (err error) {
52+
cpuInfos, err := cpu.InfoWithContext(ctx)
53+
if err != nil {
54+
return err
55+
}
56+
57+
if len(cpuInfos) > 0 {
58+
cpuInfo = &cpuInfos[0]
59+
return
60+
}
61+
62+
return errors.New("no cpu info")
63+
})
64+
g.Go(func() (err error) {
65+
cpuPercents, err := cpu.PercentWithContext(ctx, time.Second, false)
66+
if len(cpuPercents) > 0 {
67+
cpuPercent = mathutil.RoundToFloat(cpuPercents[0], 2)
68+
}
69+
return
70+
})
71+
g.Go(func() (err error) {
72+
dir, err = os.Getwd()
73+
return
74+
})
75+
76+
if err := g.Wait(); err != nil {
77+
return nil, err
6778
}
6879

6980
resp := &v1.DashboardResp{

0 commit comments

Comments
 (0)