ResourceUsage.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. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
  17. import Darwin
  18. #elseif os(Linux) || os(FreeBSD) || os(Android)
  19. import Glibc
  20. #else
  21. let badOS = { fatalError("unsupported OS") }()
  22. #endif
  23. import Foundation
  24. extension TimeInterval {
  25. init(_ value: timeval) {
  26. self.init(Double(value.tv_sec) + Double(value.tv_usec) * 1e-9)
  27. }
  28. }
  29. /// Holder for CPU time consumed.
  30. struct CPUTime {
  31. /// Amount of user process time consumed.
  32. var userTime: TimeInterval
  33. /// Amount of system time consumed.
  34. var systemTime: TimeInterval
  35. }
  36. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
  37. fileprivate let OUR_RUSAGE_SELF: Int32 = RUSAGE_SELF
  38. #elseif os(Linux) || os(FreeBSD) || os(Android)
  39. fileprivate let OUR_RUSAGE_SELF: Int32 = RUSAGE_SELF.rawValue
  40. #endif
  41. /// Get resource usage for this process.
  42. /// - returns: The amount of CPU resource consumed.
  43. func getResourceUsage() -> CPUTime {
  44. var usage = rusage()
  45. if getrusage(OUR_RUSAGE_SELF, &usage) == 0 {
  46. return CPUTime(
  47. userTime: TimeInterval(usage.ru_utime),
  48. systemTime: TimeInterval(usage.ru_stime)
  49. )
  50. } else {
  51. return CPUTime(userTime: 0, systemTime: 0)
  52. }
  53. }