Only some windows shell commands work via ruby? - windows

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).

Related

Is there any way to know which processes are running on which core in QNX

My system is running with QNX6.5 and it has 4 cpu cores. But I don't know which and all processes are running in each core. Is there any way to know in detail.
Thanks in advance
Processes typically run multiple threads (at least one - main thread); so the thread is actual running unit, not the process (and core affinity is settable per thread). Thus you'd need to know on which core(s) threads are running.
There is "%l" format option that tells you on what CPU particular thread is executing on:
# pidin -F "%b %50h %i %l" -p random
tid thread name cpu
1 1 0
Runmask : 0x0000007f
Inherit Mask: 0x0000007f
2 Timer Thread 1
Runmask : 0x0000007f
Inherit Mask: 0x0000007f
3 3 6
Runmask : 0x0000007f
Inherit Mask: 0x0000007f
Above we print thread id, thread name, run/inherit cpu masks and top right column is current cpu threads are running on, for the process called "random".
The best tooling for analyzing the details of process scheduling in QNX is the "System Analysis Toolkit", which uses the instrumentation features of the QNX kernel to provide a log of every scheduling event and message pass.
For QNX 6.5, the documentation can be found here: http://www.qnx.com/developers/docs/6.5.0SP1.update/index.html#./com.qnx.doc.instr_en_instr/about.html
Got the details by using below command.
pidin rmasks
which will give "pid, tid, and name" of every threads.
From the runmask value we can identify in which core it is running.
For me thread details also fine.

Windows CPU temps

How can I check CPU temp from the command line in Windows 10?
I have an older computer that I installed a pre-assembled CPU cooler with radiator from Corsair, and I think that it is failing because I get CPU overtemp messages at reboot. I realize that there are freeware apps that are capable of delivering this information, and I have installed the ASUS AI suite that goes with my motherboard and that is giving me the information that I want. But it is a little infuriating that I have to install this software to get the temperature data.
I have found a script at this link that runs in powershell that calls the temp and sets it to a variable like so:
function Get-Temperature {
$t = Get-WmiObject MSAcpi_ThermalZoneTemperature -Namespace "root/wmi"
And I guess that WMiObject is supposed to return a temperature in (degrees Kelvin)*e+2, because later in the script it does conversions which return Kelvin, Celsius and Farenheit. However, when I run it on my machine it returns 0 Kelvin and -273 Celsius and whatever that is in Fahrenheit.
I assume that something in that line is wrong? Can you help?

How to to stop a machine from sleeping/hibernating for execution period

I have an app written in golang (partially), as part of its operation it will spawn an external process (written in c) and begin monitoring. This external process can take many hours to complete so I am looking for a way to prevent the machine from sleeping or hibernating whilst processing.
I would like to be able to then relinquish this lock so that when the process is finished the machine is allowed to sleep/hibernate
I am initially targeting windows, but a cross-platform solution would be ideal (does nix even hibernate?).
Thanks to Anders for pointing me in the right direction - I put together a minimal example in golang (see below).
Note: polling to reset the timer seems to be the only reliable method, I found that when trying to combine with the continuous flag it would only take effect for approx 30 seconds (no idea why), having said that polling on this example is excessive and could probably be increased to 10 mins (since min hibernation time is 15 mins)
Also FYI this is a windows specific example:
package main
import (
"log"
"syscall"
"time"
)
// Execution States
const (
EsSystemRequired = 0x00000001
EsContinuous = 0x80000000
)
var pulseTime = 10 * time.Second
func main() {
kernel32 := syscall.NewLazyDLL("kernel32.dll")
setThreadExecStateProc := kernel32.NewProc("SetThreadExecutionState")
pulse := time.NewTicker(pulseTime)
log.Println("Starting keep alive poll... (silence)")
for {
select {
case <-pulse.C:
setThreadExecStateProc.Call(uintptr(EsSystemRequired))
}
}
}
The above is tested on win 7 and 10 (not tested on Win 8 yet - presumed to work there too).
Any user request to sleep will override this method, this includes actions such as shutting the lid on a laptop (unless power management settings are altered from defaults)
The above were sensible behaviors for my application.
On Windows, your first step is to try SetThreadExecutionState:
Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running
This is not a perfect solution but I assume this is not an issue for you:
The SetThreadExecutionState function cannot be used to prevent the user from putting the computer to sleep. Applications should respect that the user expects a certain behavior when they close the lid on their laptop or press the power button
The Windows 8 connected standby feature is also something you might need to consider. Looking at the power related APIs we find this description of PowerRequestSystemRequired:
The system continues to run instead of entering sleep after a period of user inactivity.
This request type is not honored on systems capable of connected standby. Applications should use PowerRequestExecutionRequired requests instead.
If you are dealing with tablets and other small devices then you can try to call PowerSetRequest with PowerRequestExecutionRequired to prevent this although the description of that is also not ideal:
The calling process continues to run instead of being suspended or terminated by process lifetime management mechanisms. When and how long the process is allowed to run depends on the operating system and power policy settings.
You might also want to use ShutdownBlockReasonCreate but I'm not sure if it blocks sleep/hibernate.

Transparent huge pages disabled but compact_stall is not null

We noticed large JVM pauses during garbage collection where user and system times are much smaller than the total time. [Times: user=3.99 sys=0.55, real=34.29 secs] We suspected it could be due to memory management and checked transparent and huge pages config which show both are disabled:
/sys/kernel/mm/redhat_transparent_hugepage/enabled:always [never]
/sys/kernel/mm/redhat_transparent_hugepage/defrag:[always] never
/sys/kernel/mm/redhat_transparent_hugepage/khugepaged/defrag:[yes] no
However looking at THP and related counters, we see a lot of compaction stalls:
egrep 'trans|thp|compact_' /proc/vmstat
nr_anon_transparent_hugepages 0
compact_blocks_moved 113682
compact_pages_moved 3535156
compact_pagemigrate_failed 0
compact_stall 1944
compact_fail 186
compact_success 1758
thp_fault_alloc 6
thp_fault_fallback 0
thp_collapse_alloc 15
thp_collapse_alloc_failed 0
thp_split 17
So the question is, why THP and compaction stall/fail counters are not 0 if THPs are disabled and how to disable compaction so it does not interfere with our JVM (which we believe is the reason of long GC pauses)
This is happening on RHEL6.2, 2.6.32-279.5.2.el6.x86_64, JVM 6u21 32-bit. Thanks!
To really get rid of THP you must make sure that not only the THP daemon is disabled, but also the THP defrag tool. defrag will run independent from THP, while the settings in /sys/kernel/mm/khugepaged/defrag only allow control whether the THP daemon may run defrag as well.
That means: Even if your applications don't get the (potential) benefit of THP, the defragmentation process which makes your system stall is still active.
It is encouraged to use the distribution independent path for controlling THP & defrag settings:
/sys/kernel/mm/transparent_hugepage/ (which may be a symlink to /sys/kernel/mm/redhat_transparent_hugepage)
This results in:
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
If you are running a java application and want to know whether THP/defrag is causing jvm pauses or stalls, it may be worth to have a look into your gc log. Having -XX:+PrintGcDetails enabled, you may observe "real" times that are significantly longer that the sys/user times.
In my case the following one-liner was sufficient
less gc.log | grep sys=0 | grep user=0 | grep -P "real=[1-9]"
The earliest description of the negative effects of THP is afaik this blog post by Greg Rahn: http://structureddata.org/2012/06/18/linux-6-transparent-huge-pages-and-hadoop-workloads/

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