Profiler and fixed tps

This commit is contained in:
2024-07-18 14:47:41 +08:00
parent cd01069c89
commit b4c2cdccaf
4 changed files with 93 additions and 10 deletions

39
pkg/internal/land/prof.go Normal file
View File

@@ -0,0 +1,39 @@
package land
import (
"log"
"sync/atomic"
"time"
)
type PerformanceAnalyzer struct {
tickCount int64
drawCount int64
}
func (p *PerformanceAnalyzer) Tick() {
atomic.AddInt64(&p.tickCount, 1)
}
func (p *PerformanceAnalyzer) Draw() {
atomic.AddInt64(&p.drawCount, 1)
}
func (p *PerformanceAnalyzer) KeepResetting(duration time.Duration) {
ticker := time.NewTicker(duration)
defer ticker.Stop()
for {
<-ticker.C
log.Printf("TPS: %d FPS: %d\n", atomic.LoadInt64(&p.tickCount), atomic.LoadInt64(&p.drawCount))
atomic.StoreInt64(&p.tickCount, 0)
atomic.StoreInt64(&p.drawCount, 0)
}
}
func (p *PerformanceAnalyzer) GetTPS() int64 {
return atomic.LoadInt64(&p.tickCount)
}
func (p *PerformanceAnalyzer) GetFPS() int64 {
return atomic.LoadInt64(&p.drawCount)
}

View File

@@ -2,16 +2,56 @@ package land
import (
"github.com/veandco/go-sdl2/sdl"
"time"
)
type RootObject struct {
BaseObject
Analyzer *PerformanceAnalyzer
}
func NewRootObject() *RootObject {
in := &RootObject{
Analyzer: &PerformanceAnalyzer{},
}
go in.Analyzer.KeepResetting(1 * time.Second)
return in
}
func (p *RootObject) RunEventLoop(tickDuration time.Duration) {
for {
startTime := time.Now()
p.Update()
elapsed := time.Since(startTime)
hangDuration := tickDuration - elapsed
if hangDuration > 0 {
time.Sleep(hangDuration)
}
}
}
func (p *RootObject) Update() {
p.BaseObject.Update()
p.Analyzer.Tick()
}
func (p *RootObject) Draw(pen *sdl.Renderer) {
// Render background and clear previous state
pen.SetDrawColor(77, 77, 77, 255)
pen.Clear()
// Render each child
for _, child := range p.Children {
if drawableChild, ok := child.(DrawableObject); ok {
drawableChild.Draw(pen)
}
}
p.Analyzer.Draw()
}