Source file src/math/big/escape_test.go

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package big
     6  
     7  import (
     8  	"internal/testenv"
     9  	"math/rand"
    10  	"os/exec"
    11  	"strings"
    12  	"testing"
    13  )
    14  
    15  func TestEscape(t *testing.T) {
    16  	testenv.MustHaveGoBuild(t)
    17  	// The multiplication routines create many temporary Int values,
    18  	// expecting them to be stack-allocated. Make sure none escape to the heap.
    19  	out, err := exec.Command("go", "build", "-gcflags=-m").CombinedOutput()
    20  	if err != nil {
    21  		t.Fatalf("go build -gcflags=-m: %v\n%s", err, out)
    22  	}
    23  	for line := range strings.Lines(string(out)) {
    24  		if strings.Contains(line, "natmul.go") && strings.Contains(line, "Int") && strings.Contains(line, "escapes") {
    25  			t.Error(strings.TrimSpace(line))
    26  		}
    27  	}
    28  }
    29  
    30  func TestMulAlloc(t *testing.T) {
    31  	r := rand.New(rand.NewSource(1234))
    32  	sizes := []int{karatsubaThreshold / 2, karatsubaThreshold}
    33  	for _, size := range sizes {
    34  		x := randInt(r, uint(size))
    35  		y := randInt(r, uint(size))
    36  		z := &Int{abs: make(nat, 2*uint(size))}
    37  		if n := testing.AllocsPerRun(10, func() { z.Mul(x, y) }); n >= 1 {
    38  			t.Errorf("Mul(len %d, len %d) allocates %.2f objects", size, size, n)
    39  		}
    40  	}
    41  }
    42  
    43  func TestSqrAlloc(t *testing.T) {
    44  	r := rand.New(rand.NewSource(1234))
    45  	sizes := []int{basicSqrThreshold / 2, basicSqrThreshold, karatsubaSqrThreshold}
    46  	for _, size := range sizes {
    47  		x := randInt(r, uint(size))
    48  		z := &Int{abs: make(nat, 2*uint(size))}
    49  		if n := testing.AllocsPerRun(10, func() { z.Mul(x, x) }); n >= 1 {
    50  			t.Errorf("Mul(len %d with itself) allocates %.2f objects", size, n)
    51  		}
    52  	}
    53  }
    54  

View as plain text