~eliasnaur/gio-example

ref: 1ad8d13d0f99c508d3a2528dfe349f3313acc7c5 gio-example/kitchen/main_test.go -rw-r--r-- 2.1 KiB
1ad8d13dChris Waldon windows,multiwindow: rename package for clarity 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// SPDX-License-Identifier: Unlicense OR MIT

package main

import (
	"image"
	"testing"
	"time"

	"gioui.org/app/headless"
	"gioui.org/f32"
	"gioui.org/font/gofont"
	"gioui.org/layout"
	"gioui.org/op"
	"gioui.org/widget/material"
)

func BenchmarkUI(b *testing.B)        { benchmarkUI(b, transformation{}) }
func BenchmarkUI_Offset(b *testing.B) { benchmarkUI(b, transformation{offset: true}) }
func BenchmarkUI_Scale(b *testing.B)  { benchmarkUI(b, transformation{scale: true}) }
func BenchmarkUI_Rotate(b *testing.B) { benchmarkUI(b, transformation{rotate: true}) }
func BenchmarkUI_All(b *testing.B) {
	benchmarkUI(b, transformation{offset: true, rotate: true, scale: true})
}

func benchmarkUI(b *testing.B, transform transformation) {
	th := material.NewTheme(gofont.Collection())

	w, err := headless.NewWindow(800, 600)
	if err != nil {
		b.Fatal(err)
	}
	defer w.Release()

	var layoutTime time.Duration
	var frameTime time.Duration

	b.ResetTimer()
	var ops op.Ops
	for i := 0; i < b.N; i++ {
		ops.Reset()
		gtx := layout.Context{
			Ops:         &ops,
			Constraints: layout.Exact(image.Pt(800, 600)),
		}
		addTransform(i, transform, gtx.Ops)
		layoutTime += measure(func() { kitchen(gtx, th) })
		frameTime += measure(func() { w.Frame(&ops) })
	}
	b.StopTimer()

	b.ReportMetric(float64(layoutTime.Nanoseconds())/float64(b.N), "ns/layout")
	b.ReportMetric(float64(frameTime.Nanoseconds())/float64(b.N), "ns/frame")
}

type transformation struct {
	offset bool
	rotate bool
	scale  bool
}

func addTransform(i int, transform transformation, ops *op.Ops) {
	if !(transform.offset || transform.rotate || transform.scale) {
		return
	}
	dt := float32(i)
	tr := f32.Affine2D{}
	if transform.rotate {
		angle := dt * .1
		tr = tr.Rotate(f32.Pt(300, 20), -angle)
	}
	if transform.scale {
		scale := 1.0 - dt*.5
		if scale < 0.5 {
			scale = 0.5
		}
		tr = tr.Scale(f32.Pt(300, 20), f32.Pt(scale, scale))
	}
	if transform.offset {
		offset := dt * 50
		if offset > 200 {
			offset = 200
		}
		tr = tr.Offset(f32.Pt(0, offset))
	}
	op.Affine(tr).Add(ops)
}

func measure(fn func()) time.Duration {
	start := time.Now()
	fn()
	return time.Since(start)
}