Matlab中使用FLOPS计算代码复杂度(浮点数运算次数)方法

本文主要是介绍Matlab中使用FLOPS计算代码复杂度(浮点数运算次数)方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考网址

Counting the Floating Point Operations (FLOPS) - File Exchange - MATLAB Central (mathworks.cn)

方法介绍

第1步

准备好需要计算浮点数运算次数的Matlab的.m文件。需要注意的是,尽量让代码结构尽可能简单,只调用常见的函数运算、矩阵操作等。如果代码中必须要调用自己构建的函数,则必须通过子函数将它们内部化,以便后续步骤也可以对它们进行解析。

第2步

在.m文件中代码的最后,将所有变量保存在MAT文件中,只要一行代码即可:

save "MATfileName"

如果代码中包含子函数,则上述代码改为:

save('MATfileName','-append')

第3步

分析Matlab代码,代码如下(本文最后会讲解官方示例):

profile on;
运行fileName;
profileStruct=profile('info');

第4步

调用FLOPS函数并计算浮点数运算次数

[flopTotal,Details]=FLOPS(fileName,MATfileName,profileStruct);

官方示例

1.脚本(Script)

脚本示例:

% This is just a test of FLOPS counting% Matrix dimensions
m = 3;
n = 4;
k = 5;% Matrix generation
A = rand(m,n);
B = ones(m,n);
C = randn(n,k) <= 0.5;% Test plus, minus, multiplication and division
D = A + B;
E = A * C;
F = ((A .* (A + B)) ./ (A-B)) * C;
G = bsxfun(@minus,A,mean(A));% Test linear algebra
P = rand(m);
PP = P * P';
P = chol(P*P');
[L,U] = lu(P);
[Q,R] = qr(P);
P = inv(P);
x = P \ rand(m,1);% Test statistics and math function
for r = 1:mS = sum(A);S = sin(A+2*B);
end% Test user supplied rules
R = mod(randi(100,m,n), randi(100,m,n));
g = gamma(A);% Save all variables in a MAT file for FLOPS counting
save exampleScriptMAT

计算示例:

profile on
exampleScript
profileStruct = profile('info');
[flopTotal,Details]  = FLOPS('exampleScript','exampleScriptMAT',profileStruct);

2.函数(Function,包含有子函数)

脚本示例:

function [Beta_draws,ME1,ME2] = exampleFun(Y,X,ndraws,burn_in)% Purpose: 
% Bayesian Estimate of the Probit model and the marginal effects
% -----------------------------------
% Model:
% Yi* = Xi * Beta + ui , where normalized ui ~ N(0,1)
% Yi* is unobservable. 
% If Yi* > 0, we observe Yi = 1; If Yi* <= 0, we observe Yi = 0
% -----------------------------------
% Algorithm: 
% Gibbs sampler. Proper prior Beta ~ N(mu,V).
% Posterior Beta has conjugate normal.
% Posterior latent variable follows truncated normal.
% -----------------------------------
% Usage:
% Y = dependent variable (n * 1 vector)
% X = regressors (n * k matrix)
% ndraws = number of draws in MCMC
% burn_in = number of burn-in draws in MCMC
% -----------------------------------
% Returns:
% Beta_draws = posterior draws of coefficients corresponding to the k regressors
% ME1 = marginal effects (average data)
% ME2 = marginal effects (individual average)
% -----------------------------------
% Notes: 
% Probit model is subject to normalization.
% The variance of disturbances is set to 1, and a constant is added to X.
% 
% Version: 06/2012
% Written by Hang Qian, Iowa State University
% Contact me:  matlabist@gmail.comif nargin<2;    error('Incomplete data.');      end
if nargin<3;    ndraws = 300;                                          end
if nargin<4;    burn_in = ndraws * 0.5;                                  endMissingValue = any(isnan([Y,X]),2);
if any(MissingValue)disp('There are missing values in your data.')disp(['Discard observations: ',num2str(find(MissingValue'))])FullValue = ~MissingValue;    Y = Y(FullValue);    X = X(FullValue,:);
end[nobs,nreg] = size(X);%----------------------------------------
% Prior distribution settings
%  Beta ~ N(mu,V)
% You may change the hyperparameters here if needed
prior_mu = zeros(nreg,1);
prior_V = 100 * eye(nreg);
%-----------------------------------------Beta_draws = zeros(nreg,ndraws-burn_in);
Z = X * ((X'*X)\(X'*Y));
XX = X' * X;
inv_prior_V = inv(prior_V);
truncate_lower =  -999 * (Y == 0);
truncate_upper =   999 * (Y == 1);for r = 1:ndrawsbeta_D = inv(XX + inv_prior_V);beta_d = X' * Z + inv_prior_V * prior_mu; %#ok<MINV>P = chol(beta_D);Beta_use = beta_D * beta_d + P' * randn(nreg,1); %#ok<MINV>Z = TN_RND(X*Beta_use,1,truncate_lower,truncate_upper,nobs);if r > burn_in        Beta_draws(:, r - burn_in) = Beta_use;end
endBeta_mean = mean(Beta_draws,2);
Beta_std = std(Beta_draws,0,2);% ME1 = normpdf(mean(X)*Beta_mean,0,1) * Beta_mean;
% ME2 = mean(normpdf(X*Beta_mean,0,1)) * Beta_mean;
ME1 = 1/sqrt(2*pi)*exp(-0.5*(mean(X)*Beta_mean).^2) * Beta_mean;
ME2 = mean(1/sqrt(2*pi)*exp(-0.5*(X*Beta_mean).^2)) * Beta_mean;result = cell(nreg + 1,5);
result(1,:) = {'Coeff.','Post. mean','Post. std','ME(avg. data)','ME(ind. avg.)'};          
for m = 1:nregresult(m + 1,1) = {['C(',num2str(m),')']};result(m + 1,2:5) = {Beta_mean(m),Beta_std(m),ME1(m),ME2(m)};    
enddisp(' ')
disp(result)save('exampleFunMat','-append')end%-------------------------------------------------------------------------
% Subfunction
function sample = TN_RND(mu,sigma,lb,ub,ndraws)% Purpose: 
% Generate random numbers from truncated normal distribution
% TN(lb,ub) (mu, sigma)
% -----------------------------------
% Density:
% f(x) = 1/(Phi(ub)-Phi(lb)) * phi(x,mu,sigma)
% -----------------------------------
% Algorithm: 
% Inverse CDF
% -----------------------------------
% Usage:
% mu = location parameter
% sigma = scale parameter
% lb = lower bound of the random number
% ub = upper bound of the random number
% ndraws = number of draws
% -----------------------------------
% Returns:
% sample = random numbers from TN(lb,ub) (mu, sigma)
% -----------------------------------
% Notes:
% 1. If at least one of the arguments mu,sigma,lb,ub are vectors/matrix,
%    It will return a vector/matrix random numbers with conformable size.
% 2. If there is no lower/upper bound, use Inf or some large number instead
%
% Version: 06/2012
% Written by Hang Qian, Iowa State University
% Contact me:  matlabist@gmail.comif nargin < 4; ub = 999;end
if nargin < 3; lb = -999;end
if nargin < 2; sigma = 1;end
if nargin < 1; mu = 0;endprob_ub = normcdf(ub,mu,sigma);
prob_lb = normcdf(lb,mu,sigma);
prob_diff = prob_ub - prob_lb;ndraws_check = length(prob_diff);
if nargin < 5 | ndraws_check > 1 %#ok<OR2>ndraws = ndraws_check;U = prob_diff;U(:) = rand(ndraws,1);
elseU = rand(ndraws,1);
endU_rescale = prob_lb + U .* prob_diff;
sample = norminv(U_rescale,mu,sigma);save('exampleFunMat')end

可以看到,exampleFun函数中TN_RND函数是自己构建的一个函数,且这个函数必须调用,因此需要将这个函数作为子函数内部化,并且在子函数后面也要加上保存语句,注意在保存主函数时需要加上'-append'

计算示例:

%% Example 2: MATLAB Functions
X = randn(100,3); Y = (X*[1 2 3]'+randn(100,1))>0;
profile on
[Beta_draws,ME1,ME2] = exampleFun(Y,X);
profileStruct = profile('info');
[flopTotal,Details] = FLOPS('exampleFun','exampleFunMat',profileStruct);

这篇关于Matlab中使用FLOPS计算代码复杂度(浮点数运算次数)方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/912293

相关文章

C语言中的浮点数存储详解

《C语言中的浮点数存储详解》:本文主要介绍C语言中的浮点数存储详解,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、首先明确一个概念2、接下来,讲解C语言中浮点型数存储的规则2.1、可以将上述公式分为两部分来看2.2、问:十进制小数0.5该如何存储?2.3 浮点

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音

什么是 Java 的 CyclicBarrier(代码示例)

《什么是Java的CyclicBarrier(代码示例)》CyclicBarrier是多线程协同的利器,适合需要多次同步的场景,本文通过代码示例讲解什么是Java的CyclicBarrier,感... 你的回答(口语化,面试场景)面试官:什么是 Java 的 CyclicBarrier?你:好的,我来举个例

Java使用Mail构建邮件功能的完整指南

《Java使用Mail构建邮件功能的完整指南》JavaMailAPI是一个功能强大的工具,它可以帮助开发者轻松实现邮件的发送与接收功能,本文将介绍如何使用JavaMail发送和接收邮件,希望对大家有所... 目录1、简述2、主要特点3、发送样例3.1 发送纯文本邮件3.2 发送 html 邮件3.3 发送带

Linux虚拟机不显示IP地址的解决方法(亲测有效)

《Linux虚拟机不显示IP地址的解决方法(亲测有效)》本文主要介绍了通过VMware新装的Linux系统没有IP地址的解决方法,主要步骤包括:关闭虚拟机、打开VM虚拟网络编辑器、还原VMnet8或修... 目录前言步骤0.问题情况1.关闭虚拟机2.China编程打开VM虚拟网络编辑器3.1 方法一:点击还原VM

Android WebView无法加载H5页面的常见问题和解决方法

《AndroidWebView无法加载H5页面的常见问题和解决方法》AndroidWebView是一种视图组件,使得Android应用能够显示网页内容,它基于Chromium,具备现代浏览器的许多功... 目录1. WebView 简介2. 常见问题3. 网络权限设置4. 启用 JavaScript5. D

使用DeepSeek搭建个人知识库(在笔记本电脑上)

《使用DeepSeek搭建个人知识库(在笔记本电脑上)》本文介绍了如何在笔记本电脑上使用DeepSeek和开源工具搭建个人知识库,通过安装DeepSeek和RAGFlow,并使用CherryStudi... 目录部署环境软件清单安装DeepSeek安装Cherry Studio安装RAGFlow设置知识库总

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Spring-AOP-ProceedingJoinPoint的使用详解

《Spring-AOP-ProceedingJoinPoint的使用详解》:本文主要介绍Spring-AOP-ProceedingJoinPoint的使用方式,具有很好的参考价值,希望对大家有所帮... 目录ProceedingJoinPoijsnt简介获取环绕通知方法的相关信息1.proceed()2.g