golang.org/x/tools/gopls@v0.15.3/internal/test/integration/bench/typing_test.go (about)

     1  // Copyright 2023 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 bench
     6  
     7  import (
     8  	"fmt"
     9  	"sync/atomic"
    10  	"testing"
    11  	"time"
    12  
    13  	"golang.org/x/tools/gopls/internal/protocol"
    14  )
    15  
    16  // BenchmarkTyping simulates typing steadily in a single file at different
    17  // paces.
    18  //
    19  // The key metric for this benchmark is not latency, but cpu_seconds per
    20  // operation.
    21  func BenchmarkTyping(b *testing.B) {
    22  	for _, test := range didChangeTests {
    23  		b.Run(test.repo, func(b *testing.B) {
    24  			env := getRepo(b, test.repo).sharedEnv(b)
    25  			env.OpenFile(test.file)
    26  			defer closeBuffer(b, env, test.file)
    27  
    28  			// Insert the text we'll be modifying at the top of the file.
    29  			env.EditBuffer(test.file, protocol.TextEdit{NewText: "// __TEST_PLACEHOLDER_0__\n"})
    30  			env.AfterChange()
    31  
    32  			delays := []time.Duration{
    33  				10 * time.Millisecond,  // automated changes
    34  				50 * time.Millisecond,  // very fast mashing, or fast key sequences
    35  				150 * time.Millisecond, // avg interval for 80wpm typing.
    36  			}
    37  
    38  			for _, delay := range delays {
    39  				b.Run(delay.String(), func(b *testing.B) {
    40  					if stopAndRecord := startProfileIfSupported(b, env, qualifiedName(test.repo, "typing")); stopAndRecord != nil {
    41  						defer stopAndRecord()
    42  					}
    43  					ticker := time.NewTicker(delay)
    44  					for i := 0; i < b.N; i++ {
    45  						edits := atomic.AddInt64(&editID, 1)
    46  						env.EditBuffer(test.file, protocol.TextEdit{
    47  							Range: protocol.Range{
    48  								Start: protocol.Position{Line: 0, Character: 0},
    49  								End:   protocol.Position{Line: 1, Character: 0},
    50  							},
    51  							// Increment the placeholder text, to ensure cache misses.
    52  							NewText: fmt.Sprintf("// __TEST_PLACEHOLDER_%d__\n", edits),
    53  						})
    54  						<-ticker.C
    55  					}
    56  					b.StopTimer()
    57  					ticker.Stop()
    58  					env.AfterChange() // wait for all change processing to complete
    59  				})
    60  			}
    61  		})
    62  	}
    63  }