We often meet the situation of the timing shutdown, I hereby put forward the unscheduled shutdown, is the application of our work when we can not predict when the completion of the case, for example: I usually run an algorithm in MATLAB to train a large number of data, because it is difficult to determine the length of their training (sometimes a few hours), no patience to wait , but I noticed that in the training data, the cup utilization has been 100% or 100% slightly left, we can try to write a program to wait for the CPU utilization of 0 o'clock shutdown (that is, the end of the MATLAB training). But there is a point, must be in the MATLAB program to save the data code to ensure that the parameters of training to save.
How to get CPU occupancy rate (under Win2K), I refer to the "Programming enthusiasts" "How to obtain a machine CPU occupancy rate" procedures: the main use of ntdll. DLL in the NtQuerySystemInformation API function.void Cautoshutdowndlg::getcpuusage ()
{
Get system time
Status = NtQuerySystemInformation (3,&systimeinfo,sizeof (Systimeinfo), 0);
if (status!=no_error)
{
MessageBox ("Failed to get system time!");
}
Get CPU idle Time
Status = NtQuerySystemInformation (2,&sysperfinfo,sizeof (sysperfinfo), NULL);
if (Status!= no_error)
{
MessageBox ("Failed to get CPU time");
}
if (lioldidletime.quadpart!= 0)
{
New CPU time = Newtime-oldtime
Dbcpuidletime =li64todouble (sysperfinfo.liidletime)-li64todouble (lioldidletime);
Dbsystime =li64todouble (systimeinfo.likesystemtime)-li64todouble (lioldsystime);
Get CPU Usage
uncpuusage=100-100* (Dbcpuidletime/dbsystime)/(double) sysbaseinfo.bkenumberprocessors+0.5;
}
wsprintf (CPUUsage, "%d%%", (UINT) uncpuusage);
M_scpuusage= (CString) CPUUsage;
If CPU usage ==0% then shutdown OS
if (bsetauto&& (UINT) dbcpuidletime==0)
{
MessageBox ("Shutdown os!");
ShutDown ();
}
Store new CPU idle and system time
Lioldidletime = Sysperfinfo.liidletime;
Lioldsystime = Systimeinfo.likesystemtime;
}
CPU utilization per second in the timer, if 0 off the system. The shutdown parameters are set as follows:ExitWindowsEx(EWX_SHUTDOWN|EWX_FORCE|EWX_POWEROFF,NULL);
Note here I set to force shutdown, so note to save the current data, in the MATLAB training to save the data immediately. Perhaps this kind of situation everybody rarely encounters, I This method is very simple very direct, hoped the general reader gives the good method or the suggestion.
This article supporting source code