In trying to answer a question elsewhere about cpu idle time, I came up with this:
set u to (do shell script "top -l 1 | grep 'CPU usage'") -- that's a -' lower case ell' and a 'numeral one' before the pipe
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "% idle"
set u to text item 1 of u
set AppleScript's text item delimiters to tid
last word of u as number
Surely there’s a better way with other unix tools; probably a one-liner.
And since it “flickers” quite a bit, this:
set total to 0
repeat 5 times
set u to (do shell script "top -l 1 | grep 'CPU usage'")
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "% idle"
set u to text item 1 of u
set AppleScript's text item delimiters to tid
set total to total + (last word of u)
delay 1
end repeat
total / 5
Works like a charm, jj, but awk must {print $12} to get idle time.
I checked it by running this after you showed me the awk ‘{print $n}’ trick.
set u to {}
repeat with k from 1 to 13
set b to "{print $" & k & "}"
set end of u to (do shell script "top -l 1 | grep 'CPU usage' | awk " & quoted form of b)
end repeat
u --> {"Load", "Avg:", "1.36,", "1.25,", "1.10", "CPU", "usage:", "9.1%", "user,", "44.1%", "sys,", "45.5%", "idle"}
i tried it, but it seems not to be 100% reliable - maybe it’s because I am currently on an slower/older computer (G4/400 Powerbook)? - Maybe … Top always calculates CPU idle with 0.0% at the first sample (-l1) here - I needed to use -l2 to get correct results:
Now I’m going to have to read the man pages on top again, and for tail and cut for the first time because I don’t want the percentage symbol, just the number.
ADDITION: OK, here’s the number:
set p to (do shell script "top -f -n0 -l1 | grep 'CPU usage' | tail -n1 | cut -d' ' -f18 | cut -c 1-4") as number
tail -n1 was only needed when using the -l2 option with top, because the result of grep are two lines - tail -n1 will cut away the first line then. Since you use -l1 you can omit this command.
and the last command: ‘cut -c 1-4’ could fail if the machine is under heavy processor usage and there is an idle value < 10% - i suggest replacing this with a comand that removes the percentage sign - for example:
top -f -n0 -l1 | grep ‘CPU usage’ | cut -d’ ’ -f18 | sed ‘s|%||’
Thank you, Dominik. I am not a unix wizard so never think of those things. Like an AppleScript beginner, I tend to grab stuff and modify it in simple ways.
As an AppleScript, it needs one more escape to escape the backslash before the % sign:
do shell script "top -f -n0 -l1 | grep 'CPU usage' | cut -d' ' -f18 | sed 's|\\%||'"