timings.m
上传用户:zjhyt3
上传日期:2007-07-03
资源大小:89k
文件大小:3k
源码类别:

matlab例程

开发平台:

Matlab

  1. %  Script file: timings.m
  2. %
  3. %  Purpose: 
  4. %    This program calculates the time required to 
  5. %    calculate the squares of all integers from 1 to
  6. %    10,000 in three different ways:
  7. %    1.  Using a for loop with an uninitialized output
  8. %        array.
  9. %    2.  Using a for loop with an pre-allocated output
  10. %        array.
  11. %    3.  Using vectors.
  12. %
  13. %  Record of revisions:
  14. %      Date       Programmer          Description of change
  15. %      ====       ==========          =====================
  16. %    12/08/97    S. J. Chapman        Original code 
  17. %
  18. % Define variables:
  19. %   ii, jj       -- Loop index
  20. %   average1     -- Average time for calculation 1
  21. %   average2     -- Average time for calculation 2
  22. %   average3     -- Average time for calculation 3
  23. %   maxcount     -- Number of times to loop calculation
  24. %   square       -- Array of squares
  25. %   leap_day     -- Extra day for leap year
  26. %   month        -- Month (mm)
  27. %   year         -- Year (yyyy)
  28. % Perform calculation with an uninitialized array 
  29. % "square".  This calculation is done only once 
  30. % because it is so slow.
  31. maxcount = 1;               % One repetition
  32. tic;                        % Start timer
  33. for jj = 1:maxcount        
  34.    clear square             % Clear output array
  35.    for ii = 1:10000       
  36.      square(ii) = ii^2;     % Calculate square
  37.    end
  38. end
  39. average1 = (toc)/maxcount;  % Calculate average time 
  40. % Perform calculation with a pre-allocated array 
  41. % "square".  This calculation is averaged over 10  
  42. % loops.
  43. maxcount = 10;              % One repetition
  44. tic;                        % Start timer
  45. for jj = 1:maxcount        
  46.    clear square             % Clear output array
  47.    square = zeros(1,10000); % Pre-initialize array
  48.    for ii = 1:10000       
  49.      square(ii) = ii^2;     % Calculate square
  50.    end
  51. end
  52. average2 = (toc)/maxcount;  % Calculate average time 
  53. % Perform calculation with vectors.  This calculation 
  54. % averaged over 100 executions. 
  55. maxcount = 100;             % One repetition
  56. tic;                        % Start timer
  57. for jj = 1:maxcount        
  58.    clear square             % Clear output array
  59.    ii = 1:10000;            % Set up vector
  60.    square = ii.^2;          % Calculate square
  61. end
  62. average3 = (toc)/maxcount;  % Calculate average time 
  63. % Display results
  64. fprintf('Loop / uninitialized array = %8.4fn', ...
  65.          average1);
  66. fprintf('Loop / initialized array =   %8.4fn', ...
  67.          average2);
  68. fprintf('Vectorized =                 %8.4fn', ...
  69.          average3);
  70.