我想知道是否还有更快的方法将datetime转换为字符串datestr
。
datetime每隔一行插入我的主函数中(包括其所有依赖项)。我需要时间执行那行代码。
我认为我唯一的选择是将日期时间更快地转换为字符串。
t = datetime('now');
DateString = datestr(t);
我进行了剖析,似乎被称为12570846次。总共需要16030.021秒。
我这样做的目的是获得执行该行的当前时间,并与我从其他带有时间戳的程序中获得的其他信息进行匹配。我将两个文件(带有此MATLAB代码的一个文件,以及来自其他程序的一个文件)与时间戳进行匹配。
您可以执行此操作的一种方法是将当前时间与上次循环中的时间进行比较。如果该datestring
值不同,则仅应重新计算该值。但实际上,我们可以走得更远,因为datestr
(正如您所说的)输出仅显示秒。因此,我们实际上可以忽略微秒的差异。
now
(〜128秒)下面我有一个示例循环,它缓存日期字符串表示形式。它将序列日期(以秒为单位)与生成最后一个日期字符串的日期进行比较。仅当日期字符串不同时,才更新日期字符串。
% Number of seconds in a day to convert the serial date number
secperday = 60 * 60 * 24;
% Store the current time as a reference
lasttime = now;
datestring = datestr(lasttime);
for k = 1:12570846
N = now;
seconds = round(N * secperday);
if ~isequal(lasttime, seconds)
% Update the cache
lasttime = seconds;
datestring = datestr(N);
end
% Use datestring however you want
disp(datestring)
end
clock
(〜24秒)另一个选择是使用clock
它将为您提供向量中不同的日期成分。您可以舍入代表秒和毫秒的最后一个元素。通过四舍五入可以抑制毫秒。这种方法似乎是一种更快的方法。
N = clock;
% Remove milliseconds
N(end) = round(N(end));
lasttime = N;
datestring = datestr(N);
for k = 1:12570846
N = clock;
% Ignore milliseconds
N(end) = round(N(end));
if ~isequal(N, lasttime)
lasttime = N;
datestring = datestr(N);
end
disp(datestring)
end
如果要在代码中的多个点将当前时间作为日期字符串获取,则最好创建一个包装此功能的函数。这是这种功能的一个例子。
function str = getDateString()
% Use persistent variables to cache the current value
persistent lasttime datestring
% Get the current time
thistime = clock;
% Truncate the milliseconds
thistime(end) = floor(thistime(end));
% See if the time has changed since the last time we called this
if ~isequal(thistime, lasttime)
lasttime = thistime;
% Update the cached string reprsentation
datestring = datestr(thistime);
end
str = datestring;
end
然后,您可以从代码中的任何位置调用此方法以获取日期字符串,并且仅在必要时才进行计算。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句