main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package main
  19. import (
  20. "flag"
  21. "fmt"
  22. "net"
  23. _ "net/http/pprof"
  24. "os"
  25. "os/signal"
  26. "runtime"
  27. "runtime/pprof"
  28. "time"
  29. "google.golang.org/grpc/benchmark"
  30. "google.golang.org/grpc/grpclog"
  31. "google.golang.org/grpc/internal/syscall"
  32. )
  33. var (
  34. port = flag.String("port", "50051", "Localhost port to listen on.")
  35. testName = flag.String("test_name", "", "Name of the test used for creating profiles.")
  36. )
  37. func main() {
  38. flag.Parse()
  39. if *testName == "" {
  40. grpclog.Fatalf("test name not set")
  41. }
  42. lis, err := net.Listen("tcp", ":"+*port)
  43. if err != nil {
  44. grpclog.Fatalf("Failed to listen: %v", err)
  45. }
  46. defer lis.Close()
  47. cf, err := os.Create("/tmp/" + *testName + ".cpu")
  48. if err != nil {
  49. grpclog.Fatalf("Failed to create file: %v", err)
  50. }
  51. defer cf.Close()
  52. pprof.StartCPUProfile(cf)
  53. cpuBeg := syscall.GetCPUTime()
  54. // Launch server in a separate goroutine.
  55. stop := benchmark.StartServer(benchmark.ServerInfo{Type: "protobuf", Listener: lis})
  56. // Wait on OS terminate signal.
  57. ch := make(chan os.Signal, 1)
  58. signal.Notify(ch, os.Interrupt)
  59. <-ch
  60. cpu := time.Duration(syscall.GetCPUTime() - cpuBeg)
  61. stop()
  62. pprof.StopCPUProfile()
  63. mf, err := os.Create("/tmp/" + *testName + ".mem")
  64. if err != nil {
  65. grpclog.Fatalf("Failed to create file: %v", err)
  66. }
  67. defer mf.Close()
  68. runtime.GC() // materialize all statistics
  69. if err := pprof.WriteHeapProfile(mf); err != nil {
  70. grpclog.Fatalf("Failed to write memory profile: %v", err)
  71. }
  72. fmt.Println("Server CPU utilization:", cpu)
  73. fmt.Println("Server CPU profile:", cf.Name())
  74. fmt.Println("Server Mem Profile:", mf.Name())
  75. }