github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/grpc/benchmark/server/main.go (about) 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 19 /* 20 Package main provides a server used for benchmarking. It launches a server 21 which is listening on port 50051. An example to start the server can be found 22 at: 23 go run benchmark/server/main.go -test_name=grpc_test 24 25 After starting the server, the client can be run separately and used to test 26 qps and latency. 27 */ 28 package main 29 30 import ( 31 "flag" 32 "fmt" 33 "net" 34 "os" 35 "os/signal" 36 "runtime" 37 "runtime/pprof" 38 "time" 39 40 _ "github.com/hxx258456/ccgo/gmhttp/pprof" 41 42 "github.com/hxx258456/ccgo/grpc/benchmark" 43 "github.com/hxx258456/ccgo/grpc/grpclog" 44 "github.com/hxx258456/ccgo/grpc/internal/syscall" 45 ) 46 47 var ( 48 port = flag.String("port", "50051", "Localhost port to listen on.") 49 testName = flag.String("test_name", "", "Name of the test used for creating profiles.") 50 51 logger = grpclog.Component("benchmark") 52 ) 53 54 func main() { 55 flag.Parse() 56 if *testName == "" { 57 logger.Fatalf("test name not set") 58 } 59 lis, err := net.Listen("tcp", ":"+*port) 60 if err != nil { 61 logger.Fatalf("Failed to listen: %v", err) 62 } 63 defer lis.Close() 64 65 cf, err := os.Create("/tmp/" + *testName + ".cpu") 66 if err != nil { 67 logger.Fatalf("Failed to create file: %v", err) 68 } 69 defer cf.Close() 70 pprof.StartCPUProfile(cf) 71 cpuBeg := syscall.GetCPUTime() 72 // Launch server in a separate goroutine. 73 stop := benchmark.StartServer(benchmark.ServerInfo{Type: "protobuf", Listener: lis}) 74 // Wait on OS terminate signal. 75 ch := make(chan os.Signal, 1) 76 signal.Notify(ch, os.Interrupt) 77 <-ch 78 cpu := time.Duration(syscall.GetCPUTime() - cpuBeg) 79 stop() 80 pprof.StopCPUProfile() 81 mf, err := os.Create("/tmp/" + *testName + ".mem") 82 if err != nil { 83 logger.Fatalf("Failed to create file: %v", err) 84 } 85 defer mf.Close() 86 runtime.GC() // materialize all statistics 87 if err := pprof.WriteHeapProfile(mf); err != nil { 88 logger.Fatalf("Failed to write memory profile: %v", err) 89 } 90 fmt.Println("Server CPU utilization:", cpu) 91 fmt.Println("Server CPU profile:", cf.Name()) 92 fmt.Println("Server Mem Profile:", mf.Name()) 93 }