我是靠谱客的博主 搞怪汉堡,这篇文章主要介绍matlab 中使用 tic 和 toc 计时错误matalb 中使用 tic 和 toc 计时错误,现在分享给大家,希望可以做个参考。

matalb 中使用 tic 和 toc 计时错误

我们知道 matlab 中可以使用,tic 和 toc 命令记录代码运行的时间。

复制代码
1
2
3
tic disp('hello,world') toc

如果需要自定义输出时间的形式可以这样

复制代码
1
2
3
4
tic disp('hello,world') t = toc; disp(['耗时 ',num2str(t),' s']);

但是如果是嵌套使用 tic 和 toc 命令时可能出现一些问题,比如计时不准。
看下面这段代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
close all clear clc %% tic filepath = 'F:我的文件Desktop任务2017'; % 读取出文件夹下的文件名 list = dir(filepath); names = {list.name}'; names(1:2) = []; % 生成要批量读取的文件绝对路径 filenames = fullfile(filepath,names); % 生成数据时间 len = length(filenames); t = char(names); t = t(:,1:10); t = cellstr(t); % 调用函数读取所需数据 data = cell(len,1); for i = 1:len data{i} = getxlsdata(filenames{i}); end t1 = toc; disp(['共耗时 ',num2str(t1),' s']);

其中调用的 getxlsdata 函数的代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
function needdata = getxlsdata(filename) tic stock = importdata(filename); [~,name,ext] = fileparts(filename); % 提取所需要的数据 try needdata = stock.Sheet1(:,[4 6 7 59]); catch needdata = stock.textdata.Sheet1(:,[4 6 7 59]); end t = toc; disp(['读取 ',name,ext,' 成功',',耗时 ',num2str(t),' s']); end

运行代码可以见到结果:
2018-02-05-20-58-31

很显然结果有问题,运行脚本的时间远不止 3.67 秒

这个错误的原因估计是嵌套使用 tic toc 命令导致最后匹配上面出了问题。这是在函数中调用 tic toc
,但是最后结果却出错。这就好像 tic toc 具有全局效应。这时应该指定 toc 所对应的 tic,修改
getxlsdata 函数如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
function needdata = getxlsdata(filename) s = tic; stock = importdata(filename); [~,name,ext] = fileparts(filename); % 提取所需要的数据 try needdata = stock.Sheet1(:,[4 6 7 59]); catch needdata = stock.textdata.Sheet1(:,[4 6 7 59]); end t = toc(s); disp(['读取 ',name,ext,' 成功',',耗时 ',num2str(t),' s']); end

再次运行代码,得到如下结果:

2018-02-05-21-24-42

完美解决问题

最后

以上就是搞怪汉堡最近收集整理的关于matlab 中使用 tic 和 toc 计时错误matalb 中使用 tic 和 toc 计时错误的全部内容,更多相关matlab内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部