working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,225 snippets matching: cpu

    public by cghersi  338846  1  6  0

    ASP.NET Performance monitors

    The following XML file can be used to create a new user defined Data Collector Set in the Performance Monitor Tool for Windows servers. It checks the most important performance counters for the right execution of ASP.NET Web applications. The performance counters taken into account are those reported in this article: http://mvolo.com/fix-the-3-hi
    <?xml version="1.0" encoding="UTF-16"?>
    <DataCollectorSet>
    	<Status>0</Status>
    	<Duration>600</Duration>
    	<Description>Genera un rapporto con informazioni dettagliate sullo stato delle risorse hardware locali, sui tempi di risposta del sistema e sui processi eseguiti nel computer locale. Tali informazioni consentono di identificare le possibili cause dei problemi di prestazioni. Per eseguire questo Insieme agenti di raccolta dati, è necessario essere almeno membri del gruppo Administrators locale o di un gruppo equivalente.</Description>
    	<DescriptionUnresolved>Genera un rapporto con informazioni dettagliate sullo stato delle risorse hardware locali, sui tempi di risposta del sistema e sui processi eseguiti nel computer locale. Tali informazioni consentono di identificare le possibili cause dei problemi di prestazioni. Per eseguire questo Insieme agenti di raccolta dati, è necessario essere almeno membri del gruppo Administrators locale o di un gruppo equivalente.</DescriptionUnresolved>
    	<DisplayName>
    	</DisplayName>
    	<DisplayNameUnresolved>
    	</DisplayNameUnresolved>
    	<SchedulesEnabled>-1</SchedulesEnabled>
    	<Keyword>CPU</Keyword>
    	<Keyword>Memory</Keyword>
    	<Keyword>Disk</Keyword>
    	<Keyword>Network</Keyword>
    	<Keyword>Performance</Keyword>
    	<LatestOutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000002</LatestOutputLocation>
    	<Name>ASP.NET</Name>
    	<OutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000003</OutputLocation>
    	<RootPath>%systemdrive%\PerfLogs\Admin\ASP.NET</RootPath>
    	<Segment>0</Segment>
    	<SegmentMaxDuration>0</SegmentMaxDuration>
    	<SegmentMaxSize>0</SegmentMaxSize>
    	<SerialNumber>3</SerialNumber>
    	<Server>
    	</Server>
    	<Subdirectory>
    	</Subdirectory>
    	<SubdirectoryFormat>3</SubdirectoryFormat>
    	<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
    	<Task>
    	</Task>
    	<TaskRunAsSelf>0</TaskRunAsSelf>
    	<TaskArguments>
    	</TaskArguments>
    	<TaskUserTextArguments>
    	</TaskUserTextArguments>
    	<UserAccount>SYSTEM</UserAccount>
    	<Security>O:BAG:S-1-5-21-2577573897-3235701343-559641010-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;LU)(A;;0x1301ff;;;S-1-5-80-2661322625-712705077-2999183737-3043590567-590698655)(A;ID;FA;;;SY)(A;ID;FA;;;BA)(A;ID;0x1200ab;;;LU)(A;ID;FR;;;AU)(A;ID;FR;;;LS)(A;ID;FR;;;NS)</Security>
    	<StopOnCompletion>0</StopOnCompletion>
    	<TraceDataCollector>
    		<DataCollectorType>1</DataCollectorType>
    		<Name>NT Kernel</Name>
    		<FileName>NtKernel</FileName>
    		<FileNameFormat>0</FileNameFormat>
    		<FileNameFormatPattern>
    		</FileNameFormatPattern>
    		<LogAppend>0</LogAppend>
    		<LogCircular>0</LogCircular>
    		<LogOverwrite>0</LogOverwrite>
    		<LatestOutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000002\NtKernel.etl</LatestOutputLocation>
    		<Guid>{00000000-0000-0000-0000-000000000000}</Guid>
    		<BufferSize>64</BufferSize>
    		<BuffersLost>0</BuffersLost>
    		<BuffersWritten>0</BuffersWritten>
    		<ClockType>1</ClockType>
    		<EventsLost>0</EventsLost>
    		<ExtendedModes>0</ExtendedModes>
    		<FlushTimer>0</FlushTimer>
    		<FreeBuffers>0</FreeBuffers>
    		<MaximumBuffers>200</MaximumBuffers>
    		<MinimumBuffers>0</MinimumBuffers>
    		<NumberOfBuffers>0</NumberOfBuffers>
    		<PreallocateFile>0</PreallocateFile>
    		<ProcessMode>0</ProcessMode>
    		<RealTimeBuffersLost>0</RealTimeBuffersLost>
    		<SessionName>NT Kernel Logger</SessionName>
    		<SessionThreadId>0</SessionThreadId>
    		<StreamMode>1</StreamMode>
    		<TraceDataProvider>
    			<DisplayName>{9E814AAD-3204-11D2-9A82-006008A86939}</DisplayName>
    			<FilterEnabled>0</FilterEnabled>
    			<FilterType>0</FilterType>
    			<Level>
    				<Description>Gli eventi fino a questo livello sono attivati</Description>
    				<ValueMapType>1</ValueMapType>
    				<Value>0</Value>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x0</Value>
    				</ValueMapItem>
    			</Level>
    			<KeywordsAny>
    				<Description>Gli eventi con almeno una delle parole chiave specificate sono attivati</Description>
    				<ValueMapType>2</ValueMapType>
    				<Value>0x10303</Value>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x1</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x2</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x100</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x200</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x10000</Value>
    				</ValueMapItem>
    			</KeywordsAny>
    			<KeywordsAll>
    				<Description>Gli eventi con tutte le parole chiave specificate sono attivati</Description>
    				<ValueMapType>2</ValueMapType>
    				<Value>0x0</Value>
    			</KeywordsAll>
    			<Properties>
    				<Description>I campi dati aggiuntivi specificati verranno raccolti con ogni evento</Description>
    				<ValueMapType>2</ValueMapType>
    				<Value>0</Value>
    			</Properties>
    			<Guid>{9E814AAD-3204-11D2-9A82-006008A86939}</Guid>
    		</TraceDataProvider>
    	</TraceDataCollector>
    	<PerformanceCounterDataCollector>
    		<DataCollectorType>0</DataCollectorType>
    		<Name>Performance Counter</Name>
    		<FileName>Performance Counter</FileName>
    		<FileNameFormat>1</FileNameFormat>
    		<FileNameFormatPattern>yyyyMMdd</FileNameFormatPattern>
    		<LogAppend>-1</LogAppend>
    		<LogCircular>0</LogCircular>
    		<LogOverwrite>0</LogOverwrite>
    		<LatestOutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000002\Performance Counter20130727.csv</LatestOutputLocation>
    		<DataSourceName>
    		</DataSourceName>
    		<SampleInterval>1</SampleInterval>
    		<SegmentMaxRecords>0</SegmentMaxRecords>
    		<LogFileFormat>0</LogFileFormat>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\% Managed Processor Time (estimated)</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Viewstate MAC Validation Failure</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors During Compilation</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors During Execution</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors During Preprocessing</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Unhandled During Execution</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Unhandled During Execution/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Audit Failure Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Error Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Error Events Raised/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Infrastructure Error Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Infrastructure Error Events Raised/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Request Error Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Request Error Events Raised/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Total</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Total/Sec</Counter>
    		<Counter>\ASP.NET v4.0.30319\Error Events Raised</Counter>
    		<Counter>\ASP.NET v4.0.30319\Infrastructure Error Events Raised</Counter>
    		<Counter>\ASP.NET v4.0.30319\Request Error Events Raised</Counter>
    		<Counter>\.NET CLR Exceptions\*</Counter>
    		<Counter>\.NET CLR Memory(_Global_)\% Time in GC</Counter>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\% Tempo processore gestito (stimato)</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errore di convalida MAC ViewState</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori di compilazione</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori di esecuzione.</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori di pre-elaborazione</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori non gestiti durante l'esecuzione</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori non gestiti durante l'esecuzione/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore di controllo generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore generati/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore infrastruttura generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore infrastruttura generati/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore richiesta generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore richiesta generati/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Totale errori</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Totale errori/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET v4.0.30319\Eventi errore generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET v4.0.30319\Eventi errore infrastruttura generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET v4.0.30319\Eventi errore richiesta generati</CounterDisplayName>
    		<CounterDisplayName>\Eccezioni CLR .NET\*</CounterDisplayName>
    		<CounterDisplayName>\Memoria CLR .NET(_Global_)\Percentuale tempo in GC</CounterDisplayName>
    	</PerformanceCounterDataCollector>
    	<DataManager>
    		<Enabled>-1</Enabled>
    		<CheckBeforeRunning>-1</CheckBeforeRunning>
    		<MinFreeDisk>200</MinFreeDisk>
    		<MaxSize>1024</MaxSize>
    		<MaxFolderCount>100</MaxFolderCount>
    		<ResourcePolicy>0</ResourcePolicy>
    		<ReportFileName>report.html</ReportFileName>
    		<RuleTargetFileName>report.xml</RuleTargetFileName>
    		<EventsFileName>
    		</EventsFileName>
    		<Rules>
    			<Logging level="15" file="rules.log">
    			</Logging>
    			<Import file="%systemroot%\pla\rules\Rules.System.Common.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Summary.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Performance.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.CPU.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Network.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Disk.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Memory.xml">
    			</Import>
    		</Rules>
    		<ReportSchema>
    			<Report name="systemPerformance" version="1" threshold="100">
    				<Import file="%systemroot%\pla\reports\Report.System.Common.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Summary.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Performance.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.CPU.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Network.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Disk.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Memory.xml">
    				</Import>
    			</Report>
    		</ReportSchema>
    		<FolderAction>
    			<Size>0</Size>
    			<Age>1</Age>
    			<Actions>3</Actions>
    			<SendCabTo>
    			</SendCabTo>
    		</FolderAction>
    		<FolderAction>
    			<Size>0</Size>
    			<Age>56</Age>
    			<Actions>8</Actions>
    			<SendCabTo>
    			</SendCabTo>
    		</FolderAction>
    		<FolderAction>
    			<Size>0</Size>
    			<Age>168</Age>
    			<Actions>26</Actions>
    			<SendCabTo>
    			</SendCabTo>
    		</FolderAction>
    	</DataManager>
    	<Value name="PerformanceMonitorView" type="document">
    		<OBJECT ID="DISystemMonitor" CLASSID="CLSID:C4D2D8E0-D1DD-11CE-940F-008029004347">
    			<PARAM NAME="CounterCount" VALUE="4">
    			</PARAM>
    			<PARAM NAME="Counter00001.Path" VALUE="\Processor(_Total)\% Processor Time">
    			</PARAM>
    			<PARAM NAME="Counter00001.Color" VALUE="255">
    			</PARAM>
    			<PARAM NAME="Counter00001.Width" VALUE="2">
    			</PARAM>
    			<PARAM NAME="Counter00001.LineStyle" VALUE="0">
    			</PARAM>
    			<PARAM NAME="Counter00001.ScaleFactor" VALUE="0">
    			</PARAM>
    			<PARAM NAME="Counter00001.Show" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00001.Selected" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00002.Path" VALUE="\Memory\Pages/sec">
    			</PARAM>
    			<PARAM NAME="Counter00002.Color" VALUE="65280">
    			</PARAM>
    			<PARAM NAME="Counter00002.Width" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00003.Path" VALUE="\PhysicalDisk(_Total)\Avg. Disk sec/Read">
    			</PARAM>
    			<PARAM NAME="Counter00003.Color" VALUE="16711680">
    			</PARAM>
    			<PARAM NAME="Counter00003.Width" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00004.Path" VALUE="\PhysicalDisk(_Total)\Avg. Disk sec/Write">
    			</PARAM>
    			<PARAM NAME="Counter00004.Color" VALUE="55295">
    			</PARAM>
    			<PARAM NAME="Counter00004.Width" VALUE="1">
    			</PARAM>
    		</OBJECT>
    	</Value>
    </DataCollectorSet>
    

    public by cghersi  3235  5  6  2

    Detect the worst SQL queries in avg CPU time in SQL Server

    Detect worst performing sql queries which is slowing down Microsoft SQL Server, this script return top queries taxing sql server CPUs. Thanks to Patrick Akhamie: http://www.sqlservercentral.com/scripts/TOP+CPU+Queries/110012/
    use tempdb
    go
    
    IF object_id('tempdb..##FindTopCPUQueries_set1') is not null DROP TABLE [dbo].[##FindTopCPUQueries_set1]
    GO
    
    declare @ServerTime datetime = getdate()
    
    , @ConvertMiliSeconds bigint = 1000
    
    , @FilterMoreThanMiliSeconds bigint = 1
    
    , @FilterHours bigint = 2
    
    , @execution_count bigint = 2
    
    , @debugFlg bit = 0
    
    
    
    if @debugFlg=1 select @ServerTime as ServerTime, @ConvertMiliSeconds as ConvertMiliSeconds
    
    , @FilterMoreThanMiliSeconds as FilterMoreThanMiliSeconds, @FilterHours as FilterHours 
    
    , @execution_count as execution_count
    
    
    
    
    
    select TOP 300
    
    @@servername as servername,@ServerTime as runtime
    
    ,isnull(db_name(QueryText.dbid),'PreparedSQL') as DBName 
    
     ,SUBSTRING(QueryText.text, (QueryStats.statement_start_offset/2)+1, 
    
    (isnull((
    
    CASE QueryStats.statement_end_offset
    
     WHEN -1 THEN DATALENGTH(QueryText.text)
    
     WHEN 0 THEN DATALENGTH(QueryText.text)
    
     ELSE QueryStats.statement_end_offset
    
     END - QueryStats.statement_start_offset),0)/2) 
    
     + 1) AS QueryExecuted
    
    ,total_worker_time AS total_worker_time
    
    ,QueryStats.execution_count as execution_count
    
    ,statement_start_offset,statement_end_offset
    
    ,(case when QueryText.dbid is null then OBJECT_NAME(QueryText.objectid) else OBJECT_NAME(QueryText.objectid, QueryText.dbid) end) as ObjectName
    
    ,query_hash
    
    ,plan_handle
    
    ,sql_handle
    
    into ##FindTopCPUQueries_set1
    
    from sys.dm_exec_query_stats as QueryStats
    
    cross apply sys.dm_exec_sql_text(QueryStats.sql_handle) as QueryText
    
    where QueryStats.query_hash IN 
    
    (
    
    select QueryStatsBaseTable.query_hash 
    
    from sys.dm_exec_query_stats QueryStatsBaseTable
    
    where last_execution_time > DATEADD(hh,-@FilterHours,GETDATE())
    
    group by query_hash
    
    having (sum(total_worker_time)/sum(execution_count))>@ConvertMiliSeconds and sum(execution_count)>@execution_count
    
    )
    
    ORDER BY total_worker_time/execution_count DESC;
    
    
    
    if @debugFlg=1 select * from ##FindTopCPUQueries_set1 order by QueryExecuted
    
    
    
    IF object_id('tempdb..##FindTopCPUQueries_set2') is not null DROP TABLE [dbo].[##FindTopCPUQueries_set2]
    
    
    
    select 
    
    servername,runtime,max(DBName) as DBName,max(QueryExecuted) as QueryExecuted,(sum(total_worker_time)/sum(execution_count))/@ConvertMiliSeconds as AvgCPUTime
    
    ,sum(execution_count) as execution_count,query_hash, max(ObjectName) as ObjectName
    
    into ##FindTopCPUQueries_set2
    
    from ##FindTopCPUQueries_set1
    
    group by query_hash,servername,runtime
    
    order by AvgCPUTime desc
    
    
    
    
    
    select * from ##FindTopCPUQueries_set2
    
    --where QueryExecuted like 'select TOP 300%'
    
    order by AvgCPUTime desc

    public by detain  2126  10  6  1

    OpenVZ CPU Usage Totals Per VPS Per CPU/Core

    #!/bin/bash
    # CPU Usage Totals Per VPS Per CPU/Core
    # Written by Joe Huss <detain@interserver.net>
    # - This is just way better than anything else out there for gathering this info
    # Screenshots here:
    # http://forum.interserver.net/forum/threads/script-get-openvz-cpu-usage-totals-per-vps-per-cpu-core.4859/
    IFS="
    ";
    debug=0;
    if [ -e ~/.cpu_usage.last.sh ]; then
    	source ~/.cpu_usage.last.sh;
    else
    	if [ ${BASH_VERSION:0:1} -ge 4 ]; then
    		declare -A cputotals;
    		declare -A cpuidles;
    	fi;
    fi;
    if [ "${1}" = "-serialize" ]; then
    	out=serialize;
    elif [ "${1}" = "-json" ]; then
    	out=json;
    else
    	out=normal;
    fi;
    if [ ${BASH_VERSION:0:1} -lt 4 ]; then
    	totalstring="";
    	idlestring="";
    else
    	totalstring="declare -A cputotals=(";
    	idlestring="declare -A cpuidles=(";
    fi;
    prev="";
    if [ "$out" = "json" ]; then
    	echo -n "{";
    elif [ "$out" = "serialize" ]; then
    	output="";
    	vzcount=0;
    fi;
    for i in $(grep "^cpu" /proc/vz/fairsched/*/cpu.proc.stat | tr / " "  | tr : " " | awk '{ print $4 " " $6 " " $7 " " $8 " " $9 " " $10 " " $11 " " $12 " " $13 " " $14 }'); do
    	vzid="$(echo "$i" | awk '{ print $1 }')";
    	cpu="$(echo "$i" | awk '{ print $2 }')";
    	total="$(echo "$i" | awk '{ print $3 "+" $4 "+" $5 "+" $6 "+" $7 "+" $8 "+" $9}' |bc -l)";
    	idle="$(echo "$i" | awk '{ print $6 }')";
    	if [ "$debug" = "1" ]; then
    		echo "Got VPS $vzid CPU $cpu Total $total Idle $idle";
    	fi;
    	key="${vzid}_${cpu}";
    	haslast=0;
    	if [ ${BASH_VERSION:0:1} -lt 4 ]; then
    		totalstring="${totalstring}export total_${key}=\"${total}\";\n";
    		idlestring="${idlestring}export idle_${key}=\"${idle}\";\n";
    		if [ ! -z "$(eval echo "\${total_${key}}")" ]; then
    			lasttotal=$(eval echo "\${total_${key}}");
    			lastidle=$(eval echo "\${idle_${key}}");
    			haslast=1;
    		fi;
    	else
    		totalstring="${totalstring}[${key}]=\"${total}\" ";
    		idlestring="${idlestring}[${key}]=\"${idle}\" ";
    		if [ ! -z "${cputotals[${key}]}" ]; then
    			lasttotal=${cputotals[${key}]};
    			lastidle=${cpuidles[${key}]};
    			haslast=1;
    		fi;
    	fi;
    	if [ $haslast -eq 1 ]; then
    		cputotal=$(echo "${total} - ${lasttotal}" |bc -l);
    		cpuidle=$(echo "${idle} - ${lastidle}" |bc -l);
    		if [ $cputotal -eq 0 ]; then
    			usage=0;
    		else
    			usage="$(echo "100 - (${cpuidle} / ${cputotal} * 100)" | bc -l)";
    		fi;
    		if [ "$debug" = "1" ]; then
    			echo "	Got CPU Total ${cputotal} Idle ${cpuidle}, Current Total ${total} Idle ${idle}, Last Total ${lasttotal} Idle ${lastidle}";
    		fi;
    		usage="$(echo "scale=2; ${usage}/1" | bc -l)";
    		if [ "${usage:0:1}" = "." ]; then
    			usage="0${usage}";
    		fi;
    		if [ "${prev}" != "${vzid}" ]; then
    			if [ "${prev}" != "" ]; then
    				if [ "$out" = "json" ]; then
    					echo -n "},";
    				elif [ "$out" = "serialize" ]; then
    					output="${output}${coreidx}:{${coreout}}";
    					vzcount=$(($vzcount + 1));
    					coreout="";
    				else
    					echo "";
    				fi;
    			fi;
    			if [ "$out" = "json" ]; then
    				echo -n "\"${vzid}\":{";
    			elif [ "$out" = "serialize" ]; then
    				output="${output}i:${vzid};a:";
    				coreidx=0;
    			else
    				echo -n "$vzid";
    			fi;
    		fi;
    		prev="${vzid}";
    		if [ "$out" = "json" ]; then
    			if [ "${cpu}" != "cpu" ]; then
    				echo -n ",";
    			fi;
    			echo -n "\"${cpu}\":\"${usage}\"";
    		elif [ "$out" = "serialize" ]; then
    			coreout="${coreout}s:${#cpu}:\"${cpu}\";s:${#usage}:\"${usage}\";";
    			coreidx=$(($coreidx + 1));
    		else
    			echo -n " $cpu ${usage}";
    		fi;
    		#echo "$vzid $cpu ${usage}%";
    	fi;
    done
    if [ "$out" = "json" ]; then
    	echo "}}";
    elif [ "$out" = "serialize" ]; then
    					output="${output}${coreidx}:{${coreout}}";				
    					vzcount=$(($vzcount + 1));
    					output="a:${vzcount}:{${output}}"
    					echo "${output}";
    else
    	echo "";
    fi;
    if [ ${BASH_VERSION:0:1} -lt 4 ]; then
    	totalstring="${totalstring}\n";
    	idlestring="${idlestring}\n";
    else
    	totalstring="${totalstring});\nexport cputotals;\n";
    	idlestring="${idlestring});\nexport cpuidles;\n";
    fi;
    echo -e "#!/bin/bash\n${totalstring}${idlestring}" > ~/.cpu_usage.last.sh;
    

    public by cghersi  1943  0  6  0

    Finding actual number of physical cpu installed

    By Rahul Singh, 2013/01/14 The Sql Server always see Logical cpu it does not distinguish between Hyperthreaded logical cpu and physical processor using the below query we can find out actual number of physical cpu installed on the server The first column represent logical processor and second column represent actual physical processor insta
    SELECT cpu_count AS Logical_CPU_Count , cpu_count / hyperthread_ratio AS Physical_CPU_Count FROM sys.dm_os_sys_info ;

    public by detain  170  0  2  0

    mytop (Monitor mysql process list with top like screen updates and adiditonal stats like cpu/io usage)

    mytop (Monitor mysql process list with top like screen updates and adiditonal stats like cpu/io usage): mytop.sh
    #!/bin/bash
    # mytop.sh - (Monitor mysql process list with top like screen updates and adiditonal stats like cpu/io usage)
    #
    # Sample Output:
    #
    #   CPU Usage  3.29% user 1.60% system  3.37% io wait  0.00% steal 91.59% idle
    #   Up 17 days 10 hours   Load Avg 0.43 0.36 0.35   Processes 1(running) 408(total) Last PID 17825
    # +----------+------+-----------+----+---------+------+-------+------------------+
    # | Id       | User | Host      | db | Command | Time | State | Info             |
    # +----------+------+-----------+----+---------+------+-------+------------------+
    # | 49117793 | root | localhost |    | Query   | 0    |       | show processlist |
    # +----------+------+-----------+----+---------+------+-------+------------------+
    # Uptime: 1507802  Threads: 1  Questions: 880170604  Slow queries: 4631149  
    # Opens: 17561  Flush tables: 117  Open tables: 204  Queries per second avg: 583.744
    # (q)uit updating
    #
    # alternative to using this shell script is creating an alias that does it so its stored in memory instead of read from script file
    # i suggest adding this to like /etc/bashrc
    #alias mytop=' delay=1; stop=no; while [ "$stop" = "no" ]; do clear; iostat -c|grep  -v "^$" |tail -n 1 | awk "{ print \"  CPU Usage  \" \$1 \"% system  \" \$4 \"% io wait  \" \$5 \"% steal \" \$6 \"% idle\" }"; upsec=$(cut -d\. -f1 /proc/uptime); alias o="echo -n "; o "  Up "; [ $upsec -lt 120 ] && o $upsec seconds || [ $upsec -lt 7200 ] && o $(($upsec / 60)) minutes || [ $upsec -lt 172800 ] && o $(($upsec / 3600)) hours || o $(($upsec / 86400)) days $(($(($upsec % 86400)) / 3600)) hours; o " "; awk "{ print \"  Load Avg \" \$1 \" \" \$2 \" \" \$3 \"   Processes \" \$4 \"(total) Last PID \" \$5 }" /proc/loadavg | sed s#"/"#"(running) "#g; mysqladmin processlist; mysqladmin status | sed s#"Opens:"#"\nOpens:"#g; read -p "(q)uit updating" -n 1 -t $delay stopnow; [ "$stopnow" = "q" ] && stop=yes; done'
    # then just type mytop to run
    
    delay=1; 
    stop=no; 
    while [ "$stop" = "no" ]; do 
      clear;
      iostat -c|grep  -v "^$" |tail -n 1 | awk "{ print \"  CPU Usage  \" \$1 \"% system  \" \$4 \"% io wait  \" \$5 \"% steal \" \$6 \"% idle\" }";
      upsec=$(cut -d\. -f1 /proc/uptime);
      echo -n "  Up ";
      [ $upsec -lt 120 ] && echo -n $upsec seconds || [ $upsec -lt 7200 ] && echo -n $(($upsec / 60)) minutes || [ $upsec -lt 172800 ] && echo -n $(($upsec / 3600)) hours || echo -n $(($upsec / 86400)) days $(($(($upsec % 86400)) / 3600)) hours;
      echo -n " ";
      awk '{ print "  Load Avg " $1 " " $2 " " $3 "   Processes " $4 "(total) Last PID " $5 }' /proc/loadavg | sed s#"/"#"(running) "#g;
      mysqladmin processlist;
      mysqladmin status | sed s#"Opens:"#"\nOpens:"#g
      read -p "(q)uit updating" -n 1 -t $delay stopnow;
      [ "$stopnow" = "q" ] && stop=yes;
    done
    
    

    public by cghersi  3175  1  7  1

    Find worst SQL performing queries

    You might have seen a number of queries which provides you with top 10 or top 5 worst performing queries either by Logical IO’s or by CPU time or by Elapsed Time.. I have similar query but it does many more thing. I personally do not query either by total logical reads or total cpu time or total elapsed time individually. I usually use this quer
    with PerformanceMetrics
    as
    (
    select
    --dest.text,
    --statement_start_offset,
    --statement_end_offset,
    --LEN(dest.text) ln,
    substring
    (
    dest.text,
    statement_start_offset/2,
    case when statement_end_offset = -1 then LEN(dest.text)
    else statement_end_offset
    end /2
    ) as 'Text of the SQL' ,
    deqs.plan_generation_num as 'Number of times the plan was generated for this SQL',
    execution_count as 'Total Number of Times the SQL was executed',
    DENSE_RANK() over(order by execution_count desc) as 'Rank of the SQL by Total number of Executions',
    total_elapsed_time/1000 as 'Total Elapsed Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_elapsed_time desc) as 'Rank of the SQL by Total Elapsed Time',
    Max_elapsed_time/1000 as 'Maximum Elapsed Time in ms consumed by this SQL',
    min_elapsed_time/1000 as 'Minimum Elapsed Time in ms consumed by this SQL',
    total_elapsed_time/1000*nullif(execution_count,0) as 'Average Elapsed Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_elapsed_time/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Elapsed Time',
    total_worker_time as 'Total CPU Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_worker_time desc) as 'Rank of the SQL by Total CPU Time',
    Max_worker_time as 'Maximum CPU Time in ms consumed by this SQL',
    min_worker_time as 'Minimum CPU Time in ms consumed by this SQL',
    total_worker_time/nullif(execution_count,0) as 'Average CPU Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_worker_time/nullif(execution_count,0) desc) as 'Rank of the SQL by Average CPU Time',
    total_logical_reads as 'Total Logical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_reads desc) as 'Rank of the SQL by Total Logical reads',
    Max_logical_reads as 'Maximum Logical Reads Clocked by this SQL',
    min_logical_reads as 'Minimum Logical Reads Clocked by this SQL',
    total_logical_reads/nullif(execution_count,0) as 'Average Logical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_reads/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Logical reads',
    total_physical_reads as 'Total Physical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_physical_reads desc) as 'Rank of the SQL by Total Physical Reads',
    Max_physical_reads as 'Maximum Physical Reads Clocked by this SQL',
    min_physical_reads as 'Minimum Physical Reads Clocked by this SQL',
    total_physical_reads/nullif(execution_count,0) as 'Average Physical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_physical_reads/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Physical Reads',
    total_logical_writes as 'Total Logical Writes Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_writes desc) as 'Rank of the SQL by Total Logical Writes',
    Max_logical_writes as 'Maximum Logical Writes Clocked by this SQL',
    min_logical_writes as 'Minimum Logical Writes Clocked by this SQL',
    total_logical_writes/nullif(execution_count,0) as 'Average Logical Writes Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_writes/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Logical Writes',
    deqp.query_plan as 'Plan of Query'
    --similarly you can add the ranks for maximum values as well.That is quite useful in finding some of the perf issues.
    from
    sys.dm_exec_query_stats deqs
    /*F0C6560A-9AD1-448B-9521-05258EF7E3FA*/ --use a newid so that we could exclude this query from the performanc emetrics output
    outer apply sys.dm_exec_query_plan(deqs.plan_handle) deqp --sometimes the plan might not be in the cache any longer.So using outer apply
    outer apply sys.dm_exec_sql_text(deqs.sql_handle) dest --Sometimes the text is not returned by the dmv so use outer apply.
    where
    dest.text not like '%F0C6560A-9AD1-448B-9521-05258EF7E3FA%'
    )
    select
    *
    from
    PerformanceMetrics
    where
    1=1
    --apply any of these where clause in any combinations or one by one..
    --and [Rank of the SQL by Average CPU Time] <= 20 --Use this to find the top N queries by avg CPU time.
    --and [Rank of the SQL by Average Elapsed Time] <= 20 --Use this to find the top N queries by avg elspsed time.
    --and [Rank of the SQL by Average Logical reads] <= 20 --Use this to find the top N queries by avg logical reads.
    --and [Rank of the SQL by Average Physical Reads] <= 20 --Use this to find the top N queries by avg physical reads.
    and [Rank of the SQL by Total CPU Time] <= 20 --Use this to find the top N queries by total CPU time.
    and [Rank of the SQL by Total Elapsed Time] <= 20 --Use this to find the top N queries by total elapsed time.
    and [Rank of the SQL by Total Logical reads] <= 20 --Use this to find the top N queries by Total Logical reads.
    and [Rank of the SQL by Total Physical Reads] <= 20 --Use this to find the top N queries by Total Physical Reads.
    and [Rank of the SQL by Total number of Executions] <= 20 --Use this to find the top N queries by Total number of Executions.
    --and [Rank of the SQL by Average Logical Writes] <= 20 --Use this to find the top N queries by Average Logical Writes.
    and [Rank of the SQL by Total Logical Writes] <= 20 --Use this to find the top N queries by Total Logical Writes.
    
    --I usually do the query by 6 rank types together Total logical reads,Total CPU time, Total Elapsed Time , Total Execution count ,Total Physical Reads and Total Logical Writes.Sometimes I exclude last two counters if i do not get any query in the output.
    --If some queries are say in top 10 in all these 6 categories then these needs to tune first...
    --But sometime you might not get any rows at all if u use these 6 categiories in that case remove one of these categories or try one by one..

    public by msdn  1745  1  7  0

    GenerateAccessToken: Generates a serialized access token using the web token that is passed. Bearer {Header}.{Body}.Thumbprint All the 3 components are Base64 encoded individually. Since a lot of cryptography is performed...

    Generates a serialized access token using the web token that is passed. Bearer {Header}.{Body}.Thumbprint All the 3 components are Base64 encoded individually. Since a lot of cryptography is performed here, this function will be CPU intensive Json Web Security Token Signing certificate. OAuth bearer token (self-signed).
    /// <summary>
    /// Prefix for bearer tokens.
    /// </summary>
    private const string BearerTokenPrefix = "Bearer ";
    
    #region Not for sample app
    
    /// <summary>
    /// Generates a serialized access token using the web token that is passed.
    /// Bearer {Header}.{Body}.Thumbprint
    /// All the 3 components are Base64 encoded individually.
    /// Since a lot of cryptography is performed here, this function will be CPU intensive
    /// </summary>
    /// <param name="webToken">Json Web Security Token</param>
    /// <param name="signingCert">Signing certificate.</param>
    /// <returns>OAuth bearer token (self-signed).</returns>
    public static string GenerateAccessToken(
        JsonWebToken webToken, X509Certificate2 signingCert)
    {
        return String.Format(
            "{0}{1}",
            JWTTokenHelper.BearerTokenPrefix,
            JWTTokenHelper.GenerateAssertion(webToken, signingCert));
    }

    external by mtopolnik  148  0  2  0

    CpuConsumer (helper in JUnit testing that creates background CPU load)

    CpuConsumer (helper in JUnit testing that creates background CPU load): gistfile1.java
    private static final CpuConsumer cpuConsumer = new CpuConsumer();
    
    @BeforeClass
    public static void prepareCpuConsumer() {
        cpuConsumer.getReady();
    }
    
    private static class CpuConsumer {
        final int taskCount = 2 * Runtime.getRuntime().availableProcessors();
        volatile CountDownLatch workerLatch = new CountDownLatch(1);
        volatile CountDownLatch clientLatch = new CountDownLatch(0);
    
        void pause() {
            if (workerLatch.getCount() == 0) {
                workerLatch = new CountDownLatch(1);
            }
        }
        void play() throws InterruptedException {
            clientLatch = new CountDownLatch(taskCount);
            workerLatch.countDown();
            assertOpenEventually(clientLatch);
        }
        void getReady() {
            final ExecutorService ex = Executors.newFixedThreadPool(taskCount);
            for (int i = 0; i < taskCount; i++) {
                ex.execute(new Runnable() {
                    double d;
                    @Override public void run() {
                        final Random rnd = new Random();
                        while (true) {
                            try {
                                workerLatch.await();
                                clientLatch.countDown();
                            } catch (InterruptedException e) {
                                System.err.println("CPU consumer interrupted: "+d);
                                return;
                            }
                            d *= Math.pow(1.001, Math.sqrt(rnd.nextInt(100) + 2));
                            if (d > 1e48) {
                                d = 1;
                            }
                        }
                    }
                });
            }
        }
    }
    
    
    
    

    external by Marcus Puchalla  331  0  3  0

    Vagrant Config Performance (full cpu, 1/4 memory)

    Vagrant Config Performance (full cpu, 1/4 memory): Vagrantfile_example
    #taken from https://stefanwrobel.com/how-to-make-vagrant-performance-not-suck
    
    config.vm.provider "virtualbox" do |v|
      host = RbConfig::CONFIG['host_os']
    
      # Give VM 1/4 system memory & access to all cpu cores on the host
      if host =~ /darwin/
        cpus = `sysctl -n hw.ncpu`.to_i
        # sysctl returns Bytes and we need to convert to MB
        mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
      elsif host =~ /linux/
        cpus = `nproc`.to_i
        # meminfo shows KB and we need to convert to MB
        mem = `grep 'MemTotal' /proc/meminfo | sed -e 's/MemTotal://' -e 's/ kB//'`.to_i / 1024 / 4
      else # sorry Windows folks, I can't help you
        cpus = 2
        mem = 1024
      end
    
      v.customize ["modifyvm", :id, "--memory", mem]
      v.customize ["modifyvm", :id, "--cpus", cpus]
    end
    
    

    external by TheRayTracer  57  0  1  0

    Utility of functions that help to determine specific CPU features, including determining the vendor of the CPU.

    Utility of functions that help to determine specific CPU features, including determining the vendor of the CPU.: cpuid.h
    C
    #ifndef CPUID_H
    #define CPUID_H
    
    #include <memory.h>
    
    #define FAMILY_ID          0x0000F00
    #define EXT_FAMILY_ID      0x0F00000
    
    #define PENTIUM4_ID        0x0000F00
    
    #define CMPXCHG8_FLAG      0x00000100
    #define MMX_FLAG           0x00800000
    #define SSE_FLAG           0x02000000
    #define SSE2_FLAG          0x04000000
    #define SSE3_FLAG          0x00000001
    #define HT_FLAG            0x10000000
    
    #define TYPE_MASK          0x00003000
    #define FAMILY_MASK        0x00000F00
    #define MAJORSTEPPING_MASK 0x000000F0
    #define MINORSTEPPING_MASK 0x0000000F
    
    #define NUM_LOGICAL_MASK   0x00FF0000 /* EBX bits 23 thu 16 indicate logical processor count. */
    
    union
    {
       struct
       {
          unsigned int a, d;
       };
    
       long long ad;
    } ads;
    
    inline long long GetCycleNumber()
    {
    #ifdef GCC
       asm volatile ("rdtsc" : "=a" (ads.a), "=d" (ads.d));
    #else
       _asm RDTSC
       _asm mov ads.a, eax
       _asm mov ads.d, edx
    #endif
    
       return ads.ad;
    }
    
    long long GetChipHz()
    {
       LARGE_INTEGER frequency, count_before, count_after, cycle_before, cycle_after;
    
       QueryPerformanceFrequency(&frequency);
       QueryPerformanceCounter(&count_before);
       cycle_before.QuadPart = GetCycleNumber();
    
    /* Some spin-wait. */
       for (volatile int i = 0; i < 1000000; i++);
    
       QueryPerformanceCounter(&count_after);
       cycle_after.QuadPart = GetCycleNumber();
    
       return ((cycle_after.QuadPart - cycle_before.QuadPart) * frequency.QuadPart / (count_after.QuadPart - count_before.QuadPart));
    }
    
    /* Returns false on MIPS, PA-RISC, SPARC
       Returns true on Intel x86 */
    bool IsLittleEndian()
    {
       typedef union
       {
          int integer;
          char byte[4];
       } endian_test;
    
       endian_test etest;
       etest.integer = 1;
    
       return etest.byte[3] == 0;
    }
    
    /* Pass Desired CPUID input (to be used for EAX) as function parameter.
       NOTE: If function is zero (00h) then out_eax will return the maximum standard input to be used.
             Exceeding the maximum standard input will result in an Exception.
             If function is 80000000h then out_eax will return the maximum extended input to be used.
             Exceeding the maximum extended input may result in an Exception. An Intel CPU will return 80000002h information.
       Returns True if Successful. */
    BOOL CPUID(unsigned long function, unsigned long& out_eax, unsigned long& out_ebx, unsigned long& out_ecx, unsigned long& out_edx)
    {
       BOOL result = TRUE;
    
    #ifdef GCC
    /* GCC uses AT&T Assembly Syntax.
       Extended inline assembly must be used to reference local memory. */
    
       try
       {
          asm ("cpuid"
             : "=a" (out_eax), /* Statements. */
               "=b" (out_ebx), /* Output. */
               "=c" (out_ecx),
               "=d" (out_edx)
             : "a" (function)); /* Input. And No clobbered hints. */
       } catch (...) {   result = FALSE;   }
    
    #else
       unsigned long local_eax, local_ebx, local_ecx, local_edx;
       _asm pushad;
    
       __try
       {
          _asm xor edx, edx /* Hint to compiler that EDX is about to be used. */
          _asm mov eax, function
          _asm cpuid
          _asm mov local_eax, eax
          _asm mov local_ebx, ebx
          _asm mov local_ecx, ecx
          _asm mov local_edx, edx
       } __except(EXCEPTION_EXECUTE_HANDLER) {   result = FALSE;   }
    
       out_eax = local_eax;
       out_ebx = local_ebx;
       out_ecx = local_ecx;
       out_edx = local_edx;
    
       _asm popad
    #endif
    
       return result;
    }
    
    /* Returns the Vendor of the CPU. */
    void GetProcessorVendor(char* vendor)
    {
       unsigned long unused, vendor_registers[3];
    
       memcpy(vendor, "UnknownCPUID", 13);
    
       if (CPUID(0, unused, vendor_registers[0], vendor_registers[2], vendor_registers[1]) != FALSE)
       {
          memcpy(vendor + 0, &(vendor_registers[0]), 4);
          memcpy(vendor + 4, &(vendor_registers[1]), 4);
          memcpy(vendor + 8, &(vendor_registers[2]), 4);
       }
    
       return;
    }
    
    /* Returns CPU type (Intel Only, else type is zeroed), CPU family, CPU major stepping and CPU minor stepping. */
    unsigned long GetProcessorSignature(unsigned int& type, unsigned int& family, unsigned int& major_stepping, unsigned int& minor_stepping)
    {
       unsigned long unused, eax = 0;
    
       if (CPUID(1, eax, unused, unused, unused) == FALSE)
       {
          return 0;
       }
    
       type = 0;
    
       char vendor[13] = {0};
       GetProcessorVendor(vendor);
    
       if (memcmp("GenuineIntel", vendor, 12) == 0)
       {
          type = (eax & TYPE_MASK);
          type = type >> 12;
       }
    
       family = (eax & FAMILY_MASK);
       family = family >> 8;
    
       major_stepping = (eax & MAJORSTEPPING_MASK);
       major_stepping = major_stepping >> 4;
    
       minor_stepping = (eax & MINORSTEPPING_MASK);
    /* minor_stepping = minor_stepping >> 0; */
    
       return eax;
    }
    
    /* Returns TRUE if CPU supports the CMPXCHG8 instruction. */
    BOOL CheckCMPXCHG8()
    {
       unsigned long unused, edx = 0;
    
       if (CPUID(1, unused, unused, unused, edx) == FALSE)
       {
          return FALSE;
       }
    
       return (edx & CMPXCHG8_FLAG) != 0; /* Test Bit 8. */
    }
    
    /* Returns TRUE if CPU supports MMX Technology. */
    BOOL CheckMMXTechnology()
    {
       unsigned long unused, edx = 0;
    
       if (CPUID(1, unused, unused, unused, edx) == FALSE)
       {
          return FALSE;
       }
    
       return (edx & MMX_FLAG) != 0; /* Test Bit 23. */
    }
    
    /* Returns TRUE if CPU supports SEE Technology. */
    BOOL CheckSSETechnology()
    {
       unsigned long unused, edx = 0;
    
       if (CPUID(1, unused, unused, unused, edx) == FALSE)
       {
          return FALSE;
       }
    
       return (edx & SSE_FLAG) != 0; /* Test Bit 25. */
    }
    
    /* Returns TRUE if CPU supports SSE2 Technology. */
    BOOL CheckSSE2Technology()
    {
       unsigned long unused, edx = 0;
    
       if (CPUID(1, unused, unused, unused, edx) == FALSE)
       {
          return FALSE;
       }
    
       return (edx & SSE2_FLAG) != 0; /* Test Bit 26. */
    }
    
    /* Returns TRUE if CPU supports SSE3 Technology. */
    BOOL CheckSSE3Technology()
    {
       unsigned long unused, ecx = 0;
    
       if (CPUID(1, unused, unused, ecx, unused) == FALSE)
       {
          return FALSE;
       }
    
       return (ecx & SSE3_FLAG) != 0; /* Test Bit 1. */
    }
    
    /* Returns TRUE if CPU supports HT Technology. */
    BOOL CheckHTTechnology()
    {
       unsigned long unused, eax = 0, edx = 0;
    
       if (CPUID(1, eax, unused, unused, edx) == FALSE)
       {
          return FALSE;
       }
    
       if ((eax & FAMILY_ID) != PENTIUM4_ID && (eax & EXT_FAMILY_ID) == 0)
       {
          edx = 0;
       }
    
       return (edx & HT_FLAG) != 0; /* Test Bit 28. */
    }
    
    /* Returns number of Logical Processors Per Package. */
    unsigned int GetLogicalProcessors()
    {
       unsigned long unused, ebx = 0;
    
       if (CPUID(1, unused, ebx, unused, unused) == FALSE)
       {
          return 1;
       }
    
       return (ebx & NUM_LOGICAL_MASK) >> 16;
    }
    
    /* Returns TRUE if CPU supports 3DNow Technology. */
    BOOL Check3DNowTechnology()
    {
       unsigned long eax = 0, edx = 0, unused;
    
       if (CPUID(0x80000000, eax, unused, unused, unused) == FALSE)
       {
          return FALSE;
       }
    
       if (eax > 0x80000000)
       {
          if (CPUID(0x80000001, unused, unused, unused, edx) == FALSE)
          {
             return FALSE;
          }
    
          return (edx & 0x80000000) != 0; /* Test Bit 31. */
        }
    
       return FALSE;
    }
    
    #endif
    
    
    
    • Public Snippets
    • Channels Snippets