You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

98 regels
2.4 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bytes"
  17. "cloud.google.com/go/profiler"
  18. "compress/gzip"
  19. "flag"
  20. "log"
  21. "math/rand"
  22. "sync"
  23. "time"
  24. )
  25. var (
  26. service = flag.String("service", "", "service name")
  27. mutexProfiling = flag.Bool("mutex_profiling", false, "enable mutex profiling")
  28. duration = flag.Int("duration", 600, "duration of the benchmark in seconds")
  29. apiAddr = flag.String("api_address", "", "API address of the profiler (e.g. 'cloudprofiler.googleapis.com:443')")
  30. )
  31. // busywork continuously generates 1MiB of random data and compresses it
  32. // throwing away the result.
  33. func busywork(mu *sync.Mutex) {
  34. ticker := time.NewTicker(time.Duration(*duration) * time.Second)
  35. defer ticker.Stop()
  36. for {
  37. select {
  38. case <-ticker.C:
  39. return
  40. default:
  41. mu.Lock()
  42. busyworkOnce()
  43. mu.Unlock()
  44. }
  45. }
  46. }
  47. func busyworkOnce() {
  48. data := make([]byte, 1024*1024)
  49. rand.Read(data)
  50. var b bytes.Buffer
  51. gz := gzip.NewWriter(&b)
  52. if _, err := gz.Write(data); err != nil {
  53. log.Printf("Failed to write to gzip stream: %v", err)
  54. return
  55. }
  56. if err := gz.Flush(); err != nil {
  57. log.Printf("Failed to flush to gzip stream: %v", err)
  58. return
  59. }
  60. if err := gz.Close(); err != nil {
  61. log.Printf("Failed to close gzip stream: %v", err)
  62. }
  63. // Throw away the result.
  64. }
  65. func main() {
  66. flag.Parse()
  67. defer log.Printf("busybench finished profiling.")
  68. if *service == "" {
  69. log.Print("Service name must be configured using --service flag.")
  70. return
  71. }
  72. if err := profiler.Start(profiler.Config{Service: *service,
  73. MutexProfiling: *mutexProfiling,
  74. DebugLogging: true,
  75. APIAddr: *apiAddr}); err != nil {
  76. log.Printf("Failed to start the profiler: %v", err)
  77. return
  78. }
  79. mu := new(sync.Mutex)
  80. var wg sync.WaitGroup
  81. wg.Add(5)
  82. for i := 0; i < 5; i++ {
  83. go func() {
  84. defer wg.Done()
  85. busywork(mu)
  86. }()
  87. }
  88. wg.Wait()
  89. }