k8s.io/kubernetes@v1.29.3/test/images/resource-consumer/consume-cpu/consume_cpu_windows.go (about) 1 //go:build windows 2 // +build windows 3 4 /* 5 Copyright 2021 The Kubernetes Authors. 6 7 Licensed under the Apache License, Version 2.0 (the "License"); 8 you may not use this file except in compliance with the License. 9 You may obtain a copy of the License at 10 11 http://www.apache.org/licenses/LICENSE-2.0 12 13 Unless required by applicable law or agreed to in writing, software 14 distributed under the License is distributed on an "AS IS" BASIS, 15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 See the License for the specific language governing permissions and 17 limitations under the License. 18 */ 19 20 package main 21 22 import ( 23 "flag" 24 "syscall" 25 "time" 26 27 syswin "golang.org/x/sys/windows" 28 ) 29 30 type procCPUStats struct { 31 User int64 // nanoseconds spent in user mode 32 System int64 // nanoseconds spent in system mode 33 Time time.Time // when the sample was taken 34 Total int64 // total of all time fields (nanoseconds) 35 } 36 37 // Retrieves the amount of CPU time this process has used since it started. 38 func statsNow(handle syscall.Handle) (s procCPUStats) { 39 var processInfo syscall.Rusage 40 syscall.GetProcessTimes(handle, &processInfo.CreationTime, &processInfo.ExitTime, &processInfo.KernelTime, &processInfo.UserTime) 41 s.Time = time.Now() 42 s.User = processInfo.UserTime.Nanoseconds() 43 s.System = processInfo.KernelTime.Nanoseconds() 44 s.Total = s.User + s.System 45 return s 46 } 47 48 // Given stats from two time points, calculates the millicores used by this 49 // process between the two samples. 50 func usageNow(first procCPUStats, second procCPUStats) int64 { 51 dT := second.Time.Sub(first.Time).Nanoseconds() 52 dUsage := (second.Total - first.Total) 53 if dT == 0 { 54 return 0 55 } 56 return 1000 * dUsage / dT 57 } 58 59 func main() { 60 flag.Parse() 61 phandle, err := syswin.GetCurrentProcess() 62 if err != nil { 63 panic(err) 64 } 65 handle := syscall.Handle(phandle) 66 67 duration := time.Duration(*durationSec) * time.Second 68 start := time.Now() 69 first := statsNow(handle) 70 for time.Since(start) < duration { 71 currentMillicores := usageNow(first, statsNow(handle)) 72 if currentMillicores < int64(*millicores) { 73 doSomething() 74 } else { 75 time.Sleep(sleep) 76 } 77 } 78 }