前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Matlab实现采集电脑的CPU等硬件信息

Matlab实现采集电脑的CPU等硬件信息

作者头像
用户9925864
发布2024-02-22 16:04:56
2270
发布2024-02-22 16:04:56
举报
文章被收录于专栏:算法工程师的学习日志

话不多说,直接上代码

代码语言:javascript
复制
function info = cpuinfo()
% CPU数据采集
%
%   信息= CPUINFO()返回一个包含不同的结构
%  中央处理器和操作系统信息由/proc/cpu提供
%   (Unix)sysctl(Mac)或WMIC(Windows)。
%     * CPU name
%     *CPU的时钟频率
%     * CPU缓存大小 (L2)
%     *物理CPU核心
%     * 操作系统的名称和版本
%
%   参见:计算机、ISUNIX ISMAC


if isunix % 判断matlab的版本 UNIX 
    if ismac % 判断matlab的版本 Mac
        info = cpuInfoMac();
    else
        info = cpuInfoUnix();
    end
else
    info = cpuInfoWindows(); 
end


%-------------------------------------------------------------------------%
function info = cpuInfoWindows()
sysInfo = callWMIC( 'cpu' );
osInfo = callWMIC( 'os' );

info = struct( ...
    'Name', sysInfo.Name, ...
    'Clock', [sysInfo.MaxClockSpeed,' MHz'], ...
    'Cache', [sysInfo.L2CacheSize,' KB'], ...
    'NumProcessors', str2double( sysInfo.NumberOfCores ), ...
    'OSType', 'Windows', ...
    'OSVersion', osInfo.Caption ); %输出的字符串结构

%---------------------111111----------------------------------------------------%
function info = callWMIC( alias )
% 呼叫ms - dos WMIC(Windows管理)命令
olddir = pwd();  %显示当前文件夹
cd( tempdir );  % 计算机目录
sysinfo = evalc( sprintf( '!wmic %s get /value', alias ) ); %得到计算机的参数
cd( olddir );
fields = textscan( sysinfo, '%s', 'Delimiter', '\n' ); fields = fields{1};%生成cell 数据处理
fields( cellfun( 'isempty', fields ) ) = [];
% 每一行有“字段=值”,所以分开
values = cell( size( fields ) );
for ff=1:numel( fields )
    idx = find( fields{ff}=='=', 1, 'first' ); %找到一个first字符串
    if ~isempty( idx ) && idx>1
        values{ff} = strtrim( fields{ff}(idx+1:end) ); %字符串分割
        fields{ff} = strtrim( fields{ff}(1:idx-1) );
    end
end

% 删除任何重复(仅适用于双插槽电脑,我们将假设所有插座有相同的处理器)。
numResults = sum( strcmpi( fields, fields{1} ) );
if numResults>1
    % 计算核数
    numCoresEntries = find( strcmpi( fields, 'NumberOfCores' ) );
    if ~isempty( numCoresEntries )
        cores = cellfun( @str2double, values(numCoresEntries) );
        values(numCoresEntries) = {num2str( sum( cores ) )};
    end
    % 去掉重复结果
    [fields,idx] = unique(fields,'first');
    values = values(idx);
end

% 数据转换
info = cell2struct( values, fields );

%-------------------22222222------------------------------------------------------%
function info = cpuInfoMac()  %Mac和window类似
machdep = callSysCtl( 'machdep.cpu' );
hw = callSysCtl( 'hw' );
info = struct( ...
    'Name', machdep.brand_string, ...
    'Clock', [num2str(str2double(hw.cpufrequency_max)/1e6),' MHz'], ...
    'Cache', [machdep.cache.size,' KB'], ...
    'NumProcessors', str2double( machdep.core_count ), ...
    'OSType', 'Mac OS/X', ...
    'OSVersion', getOSXVersion() );

%-------------------------------------------------------------------------%
function info = callSysCtl( namespace )
infostr = evalc( sprintf( '!sysctl -a %s', namespace ) );
% Remove the prefix
infostr = strrep( infostr, [namespace,'.'], '' ); %字符串
% Now break into a structure
infostr = textscan( infostr, '%s', 'delimiter', '\n' );
infostr = infostr{1};
info = struct();
for ii=1:numel( infostr )
    colonIdx = find( infostr{ii}==':', 1, 'first' );
    if isempty( colonIdx ) || colonIdx==1 || colonIdx==length(infostr{ii})
        continue
    end
    prefix = infostr{ii}(1:colonIdx-1);
    value = strtrim(infostr{ii}(colonIdx+1:end));
    while ismember( '.', prefix )
        dotIndex = find( prefix=='.', 1, 'last' );
        suffix = prefix(dotIndex+1:end);
        prefix = prefix(1:dotIndex-1);
        value = struct( suffix, value );
    end
    info.(prefix) = value;
    
end

%-------------------3333333333------------------------------------------------------%
function vernum = getOSXVersion()%版本号
% 提取系统软件版本的操作系统版本号输出
ver = evalc('system(''sw_vers'')');%版本 执行matlab字符串 软件版本信息
vernum = regexp(ver, 'ProductVersion:\s([1234567890.]*)', 'tokens', 'once');%对字符串进行查找替换
vernum = strtrim(vernum{1});

%-------------------------------------------------------------------------%
function info = cpuInfoUnix()
txt = readCPUInfo();
cpuinfo = parseCPUInfoText( txt );

txt = readOSInfo();
osinfo = parseOSInfoText( txt );

% Merge the structures
info = cell2struct( [struct2cell( cpuinfo );struct2cell( osinfo )], ...
    [fieldnames( cpuinfo );fieldnames( osinfo )] );

%-------------------------------------------------------------------------%
function info = parseCPUInfoText( txt )
% Now parse the fields
lookup = {
    'model name', 'Name'
    'cpu Mhz', 'Clock'
    'cpu cores', 'NumProcessors'
    'cache size', 'Cache'
    };
info = struct( ...
    'Name', {''}, ...
    'Clock', {''}, ...
    'Cache', {''} );
for ii=1:numel( txt )
    if isempty( txt{ii} )
        continue;
    end
    % Look for the colon that separates the property name from the value
    colon = find( txt{ii}==':', 1, 'first' );
    if isempty( colon ) || colon==1 || colon==length( txt{ii} )
        continue;
    end
    fieldName = strtrim( txt{ii}(1:colon-1) );
    fieldValue = strtrim( txt{ii}(colon+1:end) );
    if isempty( fieldName ) || isempty( fieldValue )
        continue;
    end
    
    % Is it one of the fields we're interested in?
    idx = find( strcmpi( lookup(:,1), fieldName ) );
    if ~isempty( idx )
        newName = lookup{idx,2};
        info.(newName) = fieldValue;
    end
end

% Convert clock speed
info.Clock = [info.Clock, ' MHz'];

% Convert num cores
info.NumProcessors = str2double( info.NumProcessors );

%-----------------444444--------------------------------------------------------%
function info = parseOSInfoText( txt )
info = struct( ...
    'OSType', 'Linux', ...
    'OSVersion', '' );
% find the string "linux version" then look for the bit in brackets
[~,b] = regexp( txt, '[^\(]*\(([^\)]*)\).*', 'match', 'tokens', 'once' );
info.OSVersion = b{1}{1};

%-------------------------------------------------------------------------%
function txt = readCPUInfo()

fid = fopen( '/proc/cpuinfo', 'rt' );
if fid<0
    error( 'cpuinfo:BadPROCCPUInfo', 'Could not open /proc/cpuinfo for reading' );
end
onCleanup( @() fclose( fid ) );

txt = textscan( fid, '%s', 'Delimiter', '\n' );
txt = txt{1};

%-------------------------------------------------------------------------%
function txt = readOSInfo()

fid = fopen( '/proc/version', 'rt' );
if fid<0
    error( 'cpuinfo:BadProcVersion', 'Could not open /proc/version for reading' );
end
onCleanup( @() fclose( fid ) );
txt = textscan( fid, '%s', 'Delimiter', '\n' );
txt = txt{1};

输出结果如下

代码语言:javascript
复制
>> info = cpuinfo()

info = 

  包含以下字段的 struct:

             Name: '12th Gen Intel(R) Core(TM) i5-12500H'
            Clock: '2500 MHz'
            Cache: '9216 KB'
    NumProcessors: 12
           OSType: 'Windows'
        OSVersion: 'Microsoft Windows 11 家庭中文版'
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-02-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法工程师的学习日志 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档