Friday, 19 August 2011

Current CPU Usage

You may need to programmatically collect the current CPU Utilization. Why, is beyond me but whatever. The following script cannot be a function - because for no real reason you cant use the WAITFOR command inside of a function. So instead it's a stored procedure with OUTPUT.

CREATE PROCEDURE GetCurrentCPU
    @CPU float output
AS

/* used to store current cpu data */
declare @CPU_THEN int
declare @IDLE_THEN int

/* used to store cpu data after 1 second delay */
declare @CPU_NOW int
declare @IDLE_NOW int

/* result */
declare @CPU_PERCENT float

/* get current CPU usage */
set @CPU_THEN = @@CPU_BUSY
set @IDLE_THEN = @@IDLE

WAITFOR DELAY '000:00:01'

/* get cpu usage after short delay */
set @CPU_NOW = @@CPU_BUSY
set @IDLE_NOW = @@IDLE

set @CPU_PERCENT = (@CPU_NOW - @CPU_THEN) / ((@IDLE_NOW - @IDLE_THEN + @CPU_THEN - @CPU_NOW) * 1.00) * 100

select @CPU = CONVERT(VARCHAR, @CPU_PERCENT, 1)

return @cpu

GO