Stats.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2020, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import BenchmarkUtils
  17. import NIOConcurrencyHelpers
  18. /// Convenience holder for collected statistics.
  19. struct Stats {
  20. /// Latency statistics.
  21. var latencies = Histogram()
  22. /// Error status counts.
  23. var statuses = StatusCounts()
  24. }
  25. /// Stats with access controlled by a lock -
  26. /// Needs locking rather than event loop hopping as the driver refuses to wait shutting
  27. /// the connection immediately after the request.
  28. class StatsWithLock {
  29. private var data = Stats()
  30. private let lock = Lock()
  31. /// Record a latency value into the stats.
  32. /// - parameters:
  33. /// - latency: The value to record.
  34. func add(latency: Double) {
  35. self.lock.withLockVoid { self.data.latencies.add(value: latency) }
  36. }
  37. func add(latency: Nanoseconds) {
  38. self.add(latency: Double(latency.value))
  39. }
  40. /// Copy the data out.
  41. /// - parameters:
  42. /// - reset: If the statistics should be reset after collection or not.
  43. /// - returns: A copy of the statistics.
  44. func copyData(reset: Bool) -> Stats {
  45. return self.lock.withLock {
  46. let result = self.data
  47. if reset {
  48. self.data = Stats()
  49. }
  50. return result
  51. }
  52. }
  53. }