Is it possible to know the cpu utilization from a script [closed] - windows

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
Is there any command or possible way to know the cpu utilization in windows operating system for use on the command line or in a batch script?

To determine the usage in general, you can use mcstellar and warren's answer. You also have the option of:
List all processes:
typeperf "\Process(*)\% Processor Time" -sc 1
List all processes, take 5 samples at 10 second intervals:
typeperf "\Process(*)\% Processor Time" -si 10 -sc 5
If you want a specific process, Rtvscan for example:
typeperf "\Process(Rtvscan)\% Processor Time" -si 10 -sc 5
I found it extremely useful to just monitor all process activity over a period of time. I could then dump it to a csv file and filter in a spreadsheet to remotely diagnose issues.
The following gives me 5 minutes (at 10 second intervals) of all processes. The data includes not just % Processor Time, but IO, memory, paging, etc.
typeperf -qx "\Process" > config.txt
typeperf -cf config.txt -o perf.csv -f CSV -y -si 10 -sc 60

To monitor at 1 second intervals use:
typeperf "\processor(_total)\% processor time"
For only the current usage, use:
typeperf -sc 1 "\processor(_total)\% processor time"

here's a little vbscript that shows cpu utilization for each process
strComputer ="."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery("Select * from Win32_PerfFormattedData_PerfProc_Process",,48)
For Each obj in colProcess
If obj.Name <> "Idle" And obj.Name <> "_Total" Then
WScript.echo obj.Name & "," & obj.PercentProcessorTime
End If
Next
save as showcpu.vbs and run it on the command line as
c:\test> cscript //nologo showcpu.vbs

From the command line? Have a look at PsList in the PsTools suite.

Related

Show specific UTC for a Vb 6.0 project [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How to reflect a specific UTC in a VB 6.0 Label in a form. this program will be used by multiple computer with different desktop time so i want 1 UTC to be reflected on that Label.
you see, i'm creating a employee monitoring system for our office, this will be accessed by different computers of different employees in our office that has different desktop time depending on their client but i want my program to show Philippine time only when they're logging in to the monitoring system.
You could do something like this:
Private Sub Timer1_Timer()
Dim datUTC As Date
datUTC = Time_LocalToUTC(Now)
Me.lblCurrentTimeActual.Caption = Now
Me.lblUTCTimeActual.Caption = CStr(datUTC)
Me.lblPhilippinesTimeActual.Caption = CStr(DateAdd("h", 8, datUTC))
End Sub
Public Function Time_LocalToUTC(ByVal the_date As Date) As Date
On Error GoTo ErrorTrap
' Create a new instance of the WScript Shell
Dim oWshshell As Variant
Dim UTCOffset As Long
Set oWshshell = CreateObject("WScript.Shell")
' Copy the Universal Time clock offset from the registry this does account for daylight savings
UTCOffset = oWshshell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
'Take the present system time and add in the UTC offset from the registry. The 1440 is produced
'by taking 60 * 24 since the units for a day have 1 equaling a day
Time_LocalToUTC = the_date + (UTCOffset / 1440)
GoTo EndCleanup
ErrorTrap:
MsgBox "Error: " & Err.Description, vbOKCancel, "Error Getting UTC Time"
EndCleanup:
Set oWshshell = Nothing
End Function[enter image description here][1]

Setting Size of String Buffer When Accessing Windows Registry

I'm working on a VBScript web application that has a newly-introduced requirement to talk to the registry to pull connection string information instead of using hard-coded strings. I'm doing performance profiling because of the overhead this will introduce, and noticed in Process Monitor that reading the value returns two BUFFER OVERFLOW results before finally returning a success.
Looking online, Mark Russinovich posted about this topic a few years back, indicating that since the size of the registry entry isn't known, a default buffer of 144 bytes is used. Since there are two buffer overflow responses, the amount of time taken by the entire call is approximately doubled (and yes, I realize the difference is 40 microseconds, but with 1,000 or more page hits per second, I'm willing to invest some time in optimization).
My question is this: is there a way to tell WMI what the size of the registry value is before it tries to get it? Here's a sample of the code I'm using to access the registry:
svComputer = "." ' Local machine is simply "."
ivHKey = &H80000002 ' HKEY_LOCAL_MACHINE = &H80000002 (from WinReg.h)
svRegPath = "SOFTWARE\Path\To\My\Values"
Set oRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & svComputer & "\root\default:StdRegProv")
oRegistry.GetStringValue ivHKey, svRegPath, "Value", svValue
In VBScript strings are strings. They are however long they need to be. You don't pre-define their length. Also, if performance is that much of an issue for you, you should consider using a compiled instead of an interpreted language (or a cache for values you read before).

Only some windows shell commands work via ruby?

I'm trying to use a script to control my power options since XP doesn't give you an intuitive way to change CPU Frequency options. Here's my script so far:
meh = `cmd.exe /C POWERCFG.EXE /QUERY Portable/Laptop`
puts ""
puts meh
case input
when 1 then system('cmd.exe /C POWERCFG.EXE /CHANGE Portable/Laptop /processor-throttle-ac NONE')
when 2 then system('cmd.exe /C POWERCFG.EXE /CHANGE Portable/Laptop /processor-throttle-ac ADAPTIVE')
when 3 then `cmd.exe /C POWERCFG.EXE /CHANGE Portable/Laptop /processor-throttle-ac CONSTANT`
end
The problem is that the changes simply don't take place. If I run the same commands directly into a cmd.exe prompt, they work. It's very strange, but nothing works after the initial powercfg query. I feel like I'm missing something incredibly obvious.
How can I get the above script to run correctly?
Update:
C:\shoe>ruby freq.rb
Field Description Value
----------------- -----
Name Portable/Laptop
Numerical ID 1
Turn off monitor (AC) After 15 mins
Turn off monitor (DC) After 5 mins
Turn off hard disks (AC) After 30 mins
Turn off hard disks (DC) After 5 mins
System standby (AC) After 20 mins
System standby (DC) After 5 mins
System hibernates (AC) Not Supported
System hibernates (DC) Not Supported
Processor Throttle (AC) ADAPTIVE
Processor Throttle (DC) ADAPTIVE
Enter a number to switch portable/laptop profile to that mode.
1 - None (HIGHEST FREQUENCY MODE)
2 - Adaptive (SPEEDSTEP)
3 - Constant (LOWEST FREQUENCY MODE)
#SCRIPT IS CANCELED HERE. I've already tested the methods to change powercfg options, and they work, but they only apply to Ruby's instance of powercfg.
C:\shoe>powercfg /QUERY 1 /NUMERICAL
Field Description Value
----------------- -----
Name Portable/Laptop
Numerical ID 1
Turn off monitor (AC) After 15 mins
Turn off monitor (DC) After 5 mins
Turn off hard disks (AC) After 30 mins
Turn off hard disks (DC) After 5 mins
System standby (AC) After 20 mins
System standby (DC) After 5 mins
System hibernates (AC) Not Supported
System hibernates (DC) Not Supported
Processor Throttle (AC) CONSTANT
Processor Throttle (DC) ADAPTIVE
Script works fine (indeed, you don't need the cmd.exe /C bit); that is it works fine if "input" is an integer, not a string like "1".
Could that be the incredible obvious thing you overlooked?
This works for me (my system does not support processor_throttle, so I tested with something else).
def status
`POWERCFG.EXE /QUERY #{#scheme_name} `
end
#scheme_name = "Portable/Laptop"
puts 'Before:'
puts status
`POWERCFG.EXE /CHANGE #{#scheme_name} /disk-timeout-ac 15`
puts '_'*50
puts 'After: '
puts status
However, this code changes a scheme (kind of a profile), not neccesarily the active scheme.
try
%x[cmd.exe /C ....]
Yes without the '' tags. This works for me when i have to do thing in ruby in the shell.
Instead of running these commands directly from a system call, try writing the POWERCFG call in a .bat file and run that file via system. I have had to do that in the past for some DOS applications to run the same way that they would when executed by hand in a cmd.exe window.
Edit: Based off of the example here, I would recommend running POWERCFG /SETACTIVE Portable/Laptop after you make your changes (to make sure your changes take effect).

How can I find the exact amount of physical memory on Windows x86-32bit using Perl or any other language?

I need to know how much physical memory a windows machine has, using Perl.
I've tried using Win32::SystemInfo. However this module states the following caveat:
On Intel x86 computers with more than 2 GB and less than 4 GB of memory, the MemoryStatus function will always return 2 GB for TotalPhys. Similarly, if the total available memory is between 2 and 4 GB, AvailPhys will be rounded down to 2 GB.
So on a machine which has 2-4 GB of physical memory, I get a false answer.
Is there a way to get the correct amount of physical memory? Perhaps another module? Or directly using Win32::API?
Edit: From the comments people gave here, it looks like the limitation is in the Win32 API , and not specific to Win32::SystemInfo. However, the OS does know exactly how much physical ram is available, so there must be a way to extract that information. If not in Perl then maybe in another language?
As stated in the comments, this is an issue of GlobalMemoryStatus, as it can return answers up to 2GB. And GlobalMemoryStatusEX which solves this issue of the 2GB limit, but only works on 64 bit systems (as far as I can tell).
In the end I'm using the following Perl code, which uses Win32::OLE and WMI class Win32_PhysicalMemory, which returns the correct amount of physical memory even on 32bit systems:
use strict;
use warnings;
use English;
use Win32::OLE qw( EVENTS HRESULT in );
use Readonly;
sub get_physical_memory {
my $machine = shift || '.'; # Default to local machine
my Readonly $WMI_MEMORY_CLASS_NAME = 'Win32_PhysicalMemory';
my Readonly $MEGABYTE = 1024*1024;
my $WMI =
Win32::OLE->GetObject( "winmgmts:{impersonationLevel=impersonate,(security)}//$machine/" ) || die "Could not get Win32 object: $OS_ERROR";
my $total_capacity = 0;
foreach my $object ( in( $WMI->InstancesOf( $WMI_MEMORY_CLASS_NAME ) ) ) {
$total_capacity += $object->{Capacity};
}
my $total_capacity_in_mb = $total_capacity / $MEGABYTE;
print "Total Memory : $total_capacity_in_mb \n";
return $total_capacity_in_mb;
}
I can only assume that the caveats attending Win32::SystemInfo's results are also caveats attending the raw Win32 API calls, as Perl itself certainly has no problem handling such large numbers. In which case the possibility of extracting accurate information looks a bit bleak.
I've also heard in passing that current 32-bit versions of Windows can only use about 3.2Gb of RAM on a machine that has >= 4Gb installed, which may be hearsay, but which jibes with the limitation being in the API itself.
This information can be pulled from WMI, or using SNMP if you choose to enable SNMP on the box it will be running on. For WMI, I don't have a Perl example offhand but for a VBScript example see below.
Ref: http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx
strComputer = "."
Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")
For Each objSWbemObject In colSWbemObjectSet
Wscript.Echo "Total Physical Memory (kb): " & _
objSWbemObject.TotalPhysicalMemory
Next
Tested on my XP system and it retrieves the desired results (only 1.5GB RAM here, sorry). I'm quite sure there are WMI interfaces for Perl as well if you want to stick with Perl. If SNMP is an option, the total physical memory can be obtained from SNMP as well using one of the Perl SNMP libraries.
EDIT: Just noticed #Mr. Muskrat's comment regarding Microsoft KB http://support.microsoft.com/kb/274558 - evidently the behavior you're seeing with Perl is a limitation of the Win32 API call, so you might end up with the same results with WMI. Unfortunately I don't have a 2-4GB RAM machine to try this on to verify.

Tracking CPU and Memory usage per process

I suspect that one of my applications eats more CPU cycles than I want it to. The problem is - it happens in bursts, and just looking at the task manager doesn't help me as it shows immediate usage only.
Is there a way (on Windows) to track the history of CPU & Memory usage for some process. E.g. I will start tracking "firefox", and after an hour or so will see a graph of its CPU & memory usage during that hour.
I'm looking for either a ready-made tool or a programmatic way to achieve this.
Press Win+R, type perfmon and press Enter. When the Performance window is open, click on the + sign to add new counters to the graph. The counters are different aspects of how your PC works and are grouped by similarity into groups called "Performance Object".
For your questions, you can choose the "Process", "Memory" and "Processor" performance objects. You then can see these counters in real time
You can also specify the utility to save the performance data for your inspection later. To do this, select "Performance Logs and Alerts" in the left-hand panel. (It's right under the System Monitor console which provides us with the above mentioned counters. If it is not there, click "File" > "Add/remove snap-in", click Add and select "Performance Logs and Alerts" in the list".) From the "Performance Logs and Alerts", create a new monitoring configuration under "Counter Logs". Then you can add the counters, specify the sampling rate, the log format (binary or plain text) and log location.
Process Explorer can show total CPU time taken by a process, as well as a history graph per process.
Using perfmon.exe, I have tried using the "Private Bytes" counter under "Process" counters for tracking memory usage and it works well.
maybe you can use this. It should work for you and will report processor time for the specified process.
#echo off
: Rich Kreider <rjk#techish.net>
: report processor time for given process until process exits (could be expanded to use a PID to be more
: precise)
: Depends: typeperf
: Usage: foo.cmd <processname>
set process=%~1
echo Press CTRL-C To Stop...
:begin
for /f "tokens=2 delims=," %%c in ('typeperf "\Process(%process%)\%% Processor Time" -si 1 -sc 1 ^| find /V "\\"') do (
if %%~c==-1 (
goto :end
) else (
echo %%~c%%
goto begin
)
)
:end
echo Process seems to have terminated.
I agree, perfmon.exe allows you to add counters (right click on the right panel) for any process you want to monitor.
Performance Object: Process
Check "Select instances from list" and select firefox.
WMI is Windows Management Instrumentation, and it's built into all recent versions of Windows. It allows you to programmatically track things like CPU usage, disk I/O, and memory usage.
Perfmon.exe is a GUI front-end to this interface, and can monitor a process, write information to a log, and allow you to analyze the log after the fact. It's not the world's most elegant program, but it does get the job done.
Process Lasso is designed more for process automation and priority class optimization, not graphs. That said, it does offer per-process CPU utilization history (drawn as a white line on the graph) but it does NOT offer per-process memory utilization history.
DISCLAIMER: I am the author of Process Lasso, but am not actually endorsing it here - as there are better solutions (perfmon being the best).
The best thing ever is Windows Vista+ Resource and Performance Monitor. It can track usage of CPU, Memory, Network, and Disk accesses by processes over time. It is a great overall system information utility that should have been created long ago. Unless I am mistaken, it can track per-process CPU and memory utilization over time (amongst the other things listed).
You can also try using a C#/Perl/Java script get the utilization data using WMI Commands, and below is the steps for it.
We need to execute 2 WMI Select Queries and apply CPU% utilization formula
1. To retrieve the total number of logical process
select NumberOfLogicalProcessors from Win32_ComputerSystem
2. To retrieve the values of PercentProcessorTime, TimeStamp_Sys100NS ( CPU utilization formula has be applied get the actual utilization percentage)and WorkingSetPrivate ( RAM ) minimum of 2 times with a sleep interval of 1 second
select * from Win32_PerfRawData_PerfProc_Process where IDProcess=1234
3. Apply CPU% utilization formula
CPU%= ((p2-p1)/(t2-t1)*100)/NumberOfLogicalProcessors
p2 indicated PercentProcessorTime retrieved for the second time, and p1 indicateds the PercentProcessorTime retrieved for the first time, t2 and t1 is for TimeStamp_Sys100NS.
A sample Perl code for this can be found in the link http://www.craftedforeveryone.com/cpu-and-ram-utilization-of-an-application-using-perl-via-wmi/
This logic applies for all programming language which supports WMI queries
Although I have not tried this out, ProcDump seems like a better solution.
Description from site:
ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (using the same definition of a window hang that Windows and Task Manager use), unhandled exception monitoring and can generate dumps based on the values of system performance counters. It also can serve as a general process dump utility that you can embed in other scripts.
There was a requirement to get status and cpu / memory usage of some specific windows servers. I used below script:
This is an example of Windows Search Service.
$cpu = Get-WmiObject win32_processor
$search = get-service "WSearch"
if ($search.Status -eq 'Running')
{
$searchmem = Get-WmiObject Win32_Service -Filter "Name = 'WSearch'"
$searchid = $searchmem.ProcessID
$searchcpu1 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}
Start-Sleep -Seconds 1
$searchcpu2 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}
$searchp2p1 = $searchcpu2.PercentProcessorTime - $searchcpu1.PercentProcessorTime
$searcht2t1 = $searchcpu2.Timestamp_Sys100NS - $searchcpu1.Timestamp_Sys100NS
$searchcpu = [Math]::Round(($searchp2p1 / $searcht2t1 * 100) /$cpu.NumberOfLogicalProcessors, 1)
$searchmem = [Math]::Round($searchcpu1.WorkingSetPrivate / 1mb,1)
Write-Host 'Service is' $search.Status', Memory consumed: '$searchmem' MB, CPU Usage: '$searchcpu' %'
}
else
{
Write-Host Service is $search.Status -BackgroundColor Red
}
Hmm, I see that Process Explorer can do it, although its graphs are not too convenient. Still looking for alternative / better ways to do it.
Perfmon.exe is built into windows.
You might want to have a look at Process Lasso.
I use taskinfo for history graph of CPU/RAM/IO speed.
http://www.iarsn.com/taskinfo.html
But bursts of unresponsiveness, sounds more like interrupt time due to a falty HD/SS drive.
Under Windows 10, the Task Manager can show you cumulative CPU hours. Just head to the "App history" tab and "Delete usage history". Now leave things running for an hour or two:
What this does NOT do is break down usage in browsers by tab. Quite often inactive tabs will do a tremendous amount of work, with each open tab using energy and slowing your PC.
Download process monitor
Start Process Monitor
Set a filter if required
Enter menu Options > Profiling Events
Click "Generate thread prof‌iling events", choose the frequency, and click OK.
To see the collected historical data at any time, enter menu Tools > Process Activity Summary

Resources