|
| 1 | +// Corpus benchmark: parse every .php file under the given path and report timing. |
| 2 | +// Parsing runs across GOMAXPROCS workers with the GC disabled for the short-lived run. |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "io/fs" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "runtime" |
| 11 | + "runtime/debug" |
| 12 | + "sync" |
| 13 | + "sync/atomic" |
| 14 | + "time" |
| 15 | + |
| 16 | + "github.com/rectorphp/php-parser-in-go/pkg/conf" |
| 17 | + "github.com/rectorphp/php-parser-in-go/pkg/parser" |
| 18 | + "github.com/rectorphp/php-parser-in-go/pkg/version" |
| 19 | +) |
| 20 | + |
| 21 | +func main() { |
| 22 | + root := "." |
| 23 | + if len(os.Args) > 1 { |
| 24 | + root = os.Args[1] |
| 25 | + } |
| 26 | + |
| 27 | + phpVersion, err := version.New("8.3") |
| 28 | + if err != nil { |
| 29 | + fmt.Fprintln(os.Stderr, err) |
| 30 | + os.Exit(1) |
| 31 | + } |
| 32 | + config := conf.Config{Version: phpVersion} |
| 33 | + |
| 34 | + // short-lived process: parse throughput matters, not steady-state memory |
| 35 | + debug.SetGCPercent(-1) |
| 36 | + |
| 37 | + files := collectPHPFiles(root) |
| 38 | + |
| 39 | + start := time.Now() |
| 40 | + parsed := parseAll(files, config) |
| 41 | + elapsed := time.Since(start) |
| 42 | + |
| 43 | + fmt.Printf("parsed %d files in %d ms\n", parsed, elapsed.Milliseconds()) |
| 44 | +} |
| 45 | + |
| 46 | +// parseAll parses every file across GOMAXPROCS workers and returns the count parsed. |
| 47 | +func parseAll(files []string, config conf.Config) int64 { |
| 48 | + jobs := make(chan string, runtime.GOMAXPROCS(0)) |
| 49 | + var parsed int64 |
| 50 | + |
| 51 | + var wg sync.WaitGroup |
| 52 | + for range runtime.GOMAXPROCS(0) { |
| 53 | + wg.Go(func() { |
| 54 | + for path := range jobs { |
| 55 | + content, err := os.ReadFile(path) |
| 56 | + if err != nil { |
| 57 | + continue |
| 58 | + } |
| 59 | + // broken fixtures return an error; the parse work is what we time |
| 60 | + parser.Parse(content, config) |
| 61 | + atomic.AddInt64(&parsed, 1) |
| 62 | + } |
| 63 | + }) |
| 64 | + } |
| 65 | + |
| 66 | + for _, path := range files { |
| 67 | + jobs <- path |
| 68 | + } |
| 69 | + close(jobs) |
| 70 | + wg.Wait() |
| 71 | + |
| 72 | + return parsed |
| 73 | +} |
| 74 | + |
| 75 | +func collectPHPFiles(root string) []string { |
| 76 | + var files []string |
| 77 | + filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { |
| 78 | + if err == nil && !d.IsDir() && filepath.Ext(path) == ".php" { |
| 79 | + files = append(files, path) |
| 80 | + } |
| 81 | + return nil |
| 82 | + }) |
| 83 | + return files |
| 84 | +} |
0 commit comments