When using MATLAB to perform calculations, users sometimes need to know the four items spent by the program to evaluate the execution efficiency of the program and optimize the code
You can use 3 methods to get the time required for the program to run
1. Use the tic and toc commands
Combine the tic and toc commands to get the running time of the program
①tic command: start a timer
②toc command: Stop the timer started by the tic command, and display the time elapsed since the timer was started. If the timer is not running, the toc command returns 0
example
tic;
figure,surf(peaks(40));
t=toc;
disp(t);
The disp function will directly output the content in the Matlab command window
2. Use the clock and etime commands
① clock command
Returns a row vector with 6 elements representing the date and time using decimal numbers. Its return type is [year month day hour minute seconds], where the first five elements are integers, and seconds can be accurate to a few decimal places
The following shows the operation of the clock command
You can see that the result has actually been displayed for the first time, but it is in decimal form, which is inconvenient to read, so add a line in front of it
format short g
The effect of this line is to display 5 significant figures
The special command format in matlab is used to control the display form of the data, but this command does not affect the storage form and calculation accuracy of the data
②etime(t1,t2)
Compute the t1 and t2 time intervals in seconds
Use the clock and etime commands to get the program running time
t1=clock;
figure,surf(peaks(40));
t2=clock;
t=etime(t2,t1);
disp(['程序运行时间为:',num2str(t),'秒']);
3. Use the cputime command
The cputime command can return the CPU time occupied by the MATLAB application software since it was started
t1=cputime;
figure,surf(peaks(40));
t=cputime-t1;
disp(t);
Of these three methods, the first method is recommended. Because the latter two methods are based on the system time to calculate the running time of the program, since the operating system may periodically adjust the system time, these two methods may not be accurate.