Source of timing_functions.cpp


  1: //timing_functions.cpp
  2: //Illustrates the following time-related system functions:
  3: //time(), clock() and ctime()
  4: //Also illustrates the built-in named constant CLOCKS_PER_SEC.

  6: #include <iostream>
  7: #include <ctime>
  8: using namespace std;
  9: #pragma warning(disable:4996)

 11: int main()
 12: {
 13:     cout << "\nThis program illustrates some useful "
 14:         << "time-related functions from <ctime>. \n"
 15:         << "Study the code simultaneously with the program output.";

 17:     time_t currentTime = time(0);
 18:     cout << "\n\nHere is the current time, given as the number of\n"
 19:         "seconds after an implementation-defined base time: \n";
 20:     cout << (unsigned long) currentTime << endl;
 21:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 23:     cout << "\nHere is the current date and time: \n";
 24:     cout << ctime(&currentTime);
 25:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 27:     cout << "\nHere are ten values of the \"clock\" function,\n"
 28:         "output with an artificial delay after each one:\n";
 29:     for (int i=1; i<=10000000; i++)
 30:         if (i % 1000000 == 0) cout << clock() << endl;
 31:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 33:     cout << "\nNow we illustrate inserting a delay of "
 34:         "user-chosen length into a program.\n";
 35:     int delayTimeInSeconds;
 36:     cout << "Enter the length of the delay you wish "
 37:         "to observe, in seconds: ";
 38:     cin >> delayTimeInSeconds;  cin.ignore(80, '\n');
 39:     clock_t delayTimeInClockTicks = delayTimeInSeconds * CLOCKS_PER_SEC;
 40:     cout << "\nCheck your watch, if you wish to "
 41:         "time the delay manually, and when ready ... \n";
 42:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 43:     cout << "Now starting ... \n";
 44:     clock_t numClockTicksAtStart = clock();
 45:     while (clock() - numClockTicksAtStart < delayTimeInClockTicks)
 46:         /* Do nothing */ ;
 47:     cout << "Now finished.\n";
 48:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 49: }