~whereswaldon/gioprofiler

225a5f32790521139d88a2a74c243376ba28bc89 — Chris Waldon 6 months ago 2dcf6a8 main
chore: redirect users to x repo

Signed-off-by: Chris Waldon <christopher.waldon.dev@gmail.com>
5 files changed, 1 insertions(+), 304 deletions(-)

D LICENSE
M README.md
D go.mod
D go.sum
D profiling.go
D LICENSE => LICENSE +0 -63
@@ 1,63 0,0 @@
This project is dual-licensed under the UNLICENSE or
the MIT license with the SPDX identifier:

SPDX-License-Identifier: Unlicense OR MIT

You may use the project under the terms of either license.

Both licenses are reproduced below.

----
The MIT License (MIT)

Copyright (c) 2019 The profiling authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---



---
The UNLICENSE

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org/>
---

M README.md => README.md +1 -9
@@ 1,9 1,1 @@
## gioprofiler

[![Go Reference](https://pkg.go.dev/badge/git.sr.ht/~whereswaldon/gioprofiler.svg)](https://pkg.go.dev/git.sr.ht/~whereswaldon/gioprofiler)

Profiling tools for gio

## Licensing

Dual Unlicense/MIT
This package has been moved. You can find the up-to-date version as the `profiling` package [here](https://git.sr.ht/~whereswaldon/gio-x).

D go.mod => go.mod +0 -5
@@ 1,5 0,0 @@
module git.sr.ht/~whereswaldon/gioprofiler

go 1.15

require gioui.org v0.0.0-20201127082448-4c3de5f5d294

D go.sum => go.sum +0 -24
@@ 1,24 0,0 @@
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
gioui.org v0.0.0-20201127082448-4c3de5f5d294 h1:06lh1hU75CgIX8395wLeKi47c4hEa+m+jV7oFu9XZjs=
gioui.org v0.0.0-20201127082448-4c3de5f5d294/go.mod h1:Y+uS7hHMvku1Q+ooaoq6fYD5B2LGoT8JtFgvmYmRzTw=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

D profiling.go => profiling.go +0 -203
@@ 1,203 0,0 @@
/*
Package gioprofiler provides tools for recording frame timings for later analysis.

The simplest usage is to construct a profilier at the start of your event loop
function and to defer stopping it until the window is closed. Something like:

    func loop(w *app.Window) error {
        // log to a CSV file with a randomly-chosen name. The file's path will be
        // logged to stderr.
        recorder, err := NewRecorder(nil)
        if err != nil {
            // handle
        }
        defer recorder.Stop()

        var ops op.Ops

        for event := range window.Events() {
            switch event := event.(type) {
                case system.DestroyEvent:
                    // returning will execute the deferred call to Stop(), which
                    // flushes the CSV file.
                    return event.Err
                case system.FrameEvent:
                    gtx := layout.NewContext(&ops, event)

                    // record the last frame's timing info and prepare the next one
                    recorder.profile(gtx)

                    // lay out your UI here
            }
        }
    }

The actual disk I/O is performed by a different goroutine and will not block the UI unless it gets more than 60 frames behind.
*/
package gioprofiler

import (
	"encoding/csv"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"time"

	"gioui.org/io/profile"
	"gioui.org/layout"
)

// Timings holds frame timing information
type Timings struct {
	// When is the timestamp of the frame that this struct describes
	When          time.Time
	Total         time.Duration
	FrameDuration time.Duration
	GPUTime       time.Duration
	ZT            time.Duration
	ST            time.Duration
	CovT          time.Duration
}

func (t Timings) CSVRow() []string {
	out := []string{}
	toString := func(d time.Duration) string {
		return strconv.Itoa(int(d.Milliseconds()))
	}
	out = append(out, strconv.Itoa(int(t.When.UnixNano()/1e6)))
	out = append(out, toString(t.Total))
	out = append(out, toString(t.FrameDuration))
	out = append(out, toString(t.GPUTime))
	out = append(out, toString(t.ZT))
	out = append(out, toString(t.ST))
	out = append(out, toString(t.CovT))
	return out
}

func decode(e timedEvent) Timings {
	out := Timings{}
	var tot, fd, gpu, zt, st, covt string
	fmt.Sscanf(e.Timings, "tot: %s draw: %s gpu: %s zt: %s st: %s cov: %s", &tot, &fd, &gpu, &zt, &st, &covt)
	out.When = e.when
	out.Total, _ = time.ParseDuration(tot)
	out.FrameDuration, _ = time.ParseDuration(fd)
	out.GPUTime, _ = time.ParseDuration(gpu)
	out.ZT, _ = time.ParseDuration(zt)
	out.ST, _ = time.ParseDuration(st)
	out.CovT, _ = time.ParseDuration(covt)
	return out
}

func header() []string {
	return []string{"when(unix ms)", "tot(ms)", "draw(ms)", "gpu(ms)", "zt(ms)", "st(ms)", "cov(ms)"}
}

type timedEvent struct {
	profile.Event
	when time.Time
}

// CSVTimingRecorder captures frame timing information into a CSV file
type CSVTimingRecorder struct {
	nextEventTime time.Time
	file          *os.File
	csvWriter     *csv.Writer
	listener      chan timedEvent
	errChan       chan error
}

// NewRecorder creates a CSVTimingRecorder that will record to a CSV file
// with the provided name. If the name is nil, a temporary file will be used.
func NewRecorder(filename *string) (*CSVTimingRecorder, error) {
	var (
		err  error
		file *os.File
	)
	if filename == nil {
		file, err = ioutil.TempFile("", "profile-*.csv")
	} else {
		file, err = os.Create(*filename)
	}
	if err != nil {
		return nil, fmt.Errorf("failed opening csv file: %w", err)
	}
	recorder := &CSVTimingRecorder{}
	recorder.file = file
	recorder.csvWriter = csv.NewWriter(recorder.file)
	recorder.listener = make(chan timedEvent, 60)
	recorder.errChan = make(chan error)

	go recorder.consume()
	return recorder, nil
}

func (c *CSVTimingRecorder) consume() {
	defer close(c.errChan)
	log.Printf("Logging csv profiling to %v", c.file.Name())
	c.csvWriter.Write(header())
	for e := range c.listener {
		timing := decode(e)
		err := c.csvWriter.Write(timing.CSVRow())
		if err != nil {
			c.errChan <- err
		}
	}
	c.csvWriter.Flush()
	c.errChan <- c.csvWriter.Error()
}

// Stop shuts down the recording process and flushes all data to the
// CSV file.
func (c *CSVTimingRecorder) Stop() error {
	close(c.listener)
	err := <-c.errChan
	if err != nil {
		return fmt.Errorf("failed to flush writer: %w", err)
	}
	err = c.file.Close()
	if err != nil {
		return fmt.Errorf("failed to close csv: %w", err)
	}
	log.Printf("CSV profiling data written to %s", c.file.Name())
	return nil
}

// Profile records profiling data from the last frame and prepares the
// capture of the next frame. Calling this method every frame is sufficient
// to profile all frames. It will simply return if c is nil.
func (c *CSVTimingRecorder) Profile(gtx layout.Context) {
	if c == nil {
		return
	}
	var lastEventTime time.Time
	lastEventTime, c.nextEventTime = c.nextEventTime, gtx.Now
	profile.Op{Tag: c}.Add(gtx.Ops)
	for _, e := range gtx.Events(c) {
		switch e := e.(type) {
		case profile.Event:
			c.Write(lastEventTime, e)
		}
	}
}

// Write is a lower-level way to capture a single profile event. It should
// be used instead of the Profile method if more granular profiling control
// is desired. It will simply return if c is nil.
func (c *CSVTimingRecorder) Write(when time.Time, e profile.Event) error {
	if c == nil {
		return nil
	}
	var err error
	select {
	case err = <-c.errChan:
	default:
	}
	select {
	case c.listener <- timedEvent{Event: e, when: when}:
	default:
		err = fmt.Errorf("recorder already stopped")
	}
	return err
}