Skip to content

[perf] Profile possibly slow functions #1491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion internal/boxcli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ func Execute(ctx context.Context, args []string) int {
}

func Main() {
timer := debug.Timer(strings.Join(os.Args, " "))
ctx := context.Background()
if strings.HasSuffix(os.Args[0], "ssh") ||
strings.HasSuffix(os.Args[0], "scp") {
Expand All @@ -126,7 +127,7 @@ func Main() {
code := Execute(ctx, os.Args[1:])
// Run out here instead of as a middleware so we can capture any time we spend
// in middlewares as well.
debug.PrintExecutionTime()
timer.End()
os.Exit(code)
}

Expand Down
48 changes: 40 additions & 8 deletions internal/debug/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,54 @@ package debug
import (
"fmt"
"os"
"runtime"
"strconv"
"strings"
"time"
)

var timerEnabled, _ = strconv.ParseBool(os.Getenv(devboxPrintExecTime))

const devboxPrintExecTime = "DEVBOX_PRINT_EXEC_TIME"

var start = time.Now()
var headerPrinted = false

type timer struct {
name string
time time.Time
}

func Timer(name string) *timer {
if !timerEnabled {
return nil
}
return &timer{
name: name,
time: time.Now(),
}
}

func FunctionTimer() *timer {
if !timerEnabled {
return nil
}
pc := make([]uintptr, 15)
n := runtime.Callers(2, pc)
frames := runtime.CallersFrames(pc[:n])
frame, _ := frames.Next()
parts := strings.Split(frame.Function, ".")
return Timer(parts[len(parts)-1])
}

func PrintExecutionTime() {
if enabled, _ := strconv.ParseBool(os.Getenv(devboxPrintExecTime)); !enabled {
func (t *timer) End() {
if t == nil {
return
}
fmt.Fprintf(
os.Stderr,
"\"%s\" took %s\n", strings.Join(os.Args, " "),
time.Since(start),
)
if !headerPrinted {
fmt.Fprintln(os.Stderr, "\nExec times over 1ms:")
headerPrinted = true
}
if time.Since(t.time) >= time.Millisecond {
fmt.Fprintf(os.Stderr, "\"%s\" took %s\n", t.name, time.Since(t.time))
}
}
1 change: 1 addition & 0 deletions internal/impl/devbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,7 @@ var nixEnvCache map[string]string
// Note that this is in-memory cache of the final environment, and not the same
// as the nix print-dev-env cache which is stored in a file.
func (d *Devbox) nixEnv(ctx context.Context) (map[string]string, error) {
defer debug.FunctionTimer().End()
if nixEnvCache != nil {
return nixEnvCache, nil
}
Expand Down
2 changes: 2 additions & 0 deletions internal/impl/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ const (
// what operations are happening, because this function may take time to execute.
func (d *Devbox) ensurePackagesAreInstalled(ctx context.Context, mode installMode) error {
defer trace.StartRegion(ctx, "ensurePackages").End()
defer debug.FunctionTimer().End()

if upToDate, err := d.lockfile.IsUpToDateAndInstalled(); err != nil || upToDate {
return err
Expand Down Expand Up @@ -266,6 +267,7 @@ func (d *Devbox) profilePath() (string, error) {
// syncPackagesToProfile ensures that all packages in devbox.json exist in the nix profile,
// and no more.
func (d *Devbox) syncPackagesToProfile(ctx context.Context, mode installMode) error {
defer debug.FunctionTimer().End()
// TODO: we can probably merge these two operations to be faster and minimize chances of
// the devbox.json and nix profile falling out of sync.
if err := d.addPackagesToProfile(ctx, mode); err != nil {
Expand Down
1 change: 1 addition & 0 deletions internal/shellgen/scripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type devboxer interface {
// WriteScriptsToFiles writes scripts defined in devbox.json into files inside .devbox/gen/scripts.
// Scripts (and hooks) are persisted so that we can easily call them from devbox run (inside or outside shell).
func WriteScriptsToFiles(devbox devboxer) error {
defer debug.FunctionTimer().End()
err := os.MkdirAll(filepath.Join(devbox.ProjectDir(), scriptsDir), 0755) // Ensure directory exists.
if err != nil {
return errors.WithStack(err)
Expand Down
1 change: 1 addition & 0 deletions internal/wrapnix/wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ var devboxSymlinkDir = xdg.CacheSubpath(filepath.Join("devbox", "bin", "current"

// CreateWrappers creates wrappers for all the executables in nix paths
func CreateWrappers(ctx context.Context, devbox devboxer) error {
defer debug.FunctionTimer().End()
shellEnvHash, err := devbox.ShellEnvHash(ctx)
if err != nil {
return err
Expand Down