| 1 | // Copyright 2018 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 packages_test |
| 6 | |
| 7 | import ( |
| 8 | "runtime" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "golang.org/x/tools/go/packages" |
| 13 | "golang.org/x/tools/internal/testenv" |
| 14 | ) |
| 15 | |
| 16 | // This test loads the metadata for the standard library, |
| 17 | func TestStdlibMetadata(t *testing.T) { |
| 18 | testenv.NeedsGoPackages(t) |
| 19 | |
| 20 | runtime.GC() |
| 21 | t0 := time.Now() |
| 22 | var memstats runtime.MemStats |
| 23 | runtime.ReadMemStats(&memstats) |
| 24 | alloc := memstats.Alloc |
| 25 | |
| 26 | // Load, parse and type-check the program. |
| 27 | cfg := &packages.Config{Mode: packages.LoadAllSyntax} |
| 28 | pkgs, err := packages.Load(cfg, "std") |
| 29 | if err != nil { |
| 30 | t.Fatalf("failed to load metadata: %v", err) |
| 31 | } |
| 32 | if packages.PrintErrors(pkgs) > 0 { |
| 33 | t.Fatal("there were errors loading standard library") |
| 34 | } |
| 35 | |
| 36 | t1 := time.Now() |
| 37 | runtime.GC() |
| 38 | runtime.ReadMemStats(&memstats) |
| 39 | runtime.KeepAlive(pkgs) |
| 40 | |
| 41 | t.Logf("Loaded %d packages", len(pkgs)) |
| 42 | numPkgs := len(pkgs) |
| 43 | |
| 44 | want := 150 // 186 on linux, 185 on windows. |
| 45 | if numPkgs < want { |
| 46 | t.Errorf("Loaded only %d packages, want at least %d", numPkgs, want) |
| 47 | } |
| 48 | |
| 49 | t.Log("GOMAXPROCS: ", runtime.GOMAXPROCS(0)) |
| 50 | t.Log("Metadata: ", t1.Sub(t0)) // ~800ms on 12 threads |
| 51 | t.Log("#MB: ", int64(memstats.Alloc-alloc)/1000000) // ~1MB |
| 52 | } |
| 53 | |
| 54 | // BenchmarkNetHTTP measures the time to load/parse/typecheck the |
| 55 | // net/http package and all dependencies. |
| 56 | func BenchmarkNetHTTP(b *testing.B) { |
| 57 | testenv.NeedsGoPackages(b) |
| 58 | b.ReportAllocs() |
| 59 | |
| 60 | var bytes int64 |
| 61 | |
| 62 | for i := range b.N { |
| 63 | cfg := &packages.Config{Mode: packages.LoadAllSyntax} |
| 64 | pkgs, err := packages.Load(cfg, "net/http") |
| 65 | if err != nil { |
| 66 | b.Fatalf("failed to load metadata: %v", err) |
| 67 | } |
| 68 | if packages.PrintErrors(pkgs) > 0 { |
| 69 | b.Fatal("there were errors loading net/http") |
| 70 | } |
| 71 | |
| 72 | if i == 0 { |
| 73 | for pkg := range packages.Postorder(pkgs) { |
| 74 | for _, f := range pkg.Syntax { |
| 75 | bytes += int64(f.FileEnd - f.FileStart) |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | b.SetBytes(bytes) // total source bytes |
| 82 | } |