2.11.5. Some useful functions

Learning objectives

Useful functions from misc.h
Measuring running times with used_time()

LEDA has a small number of useful functions ready, which are declared in the header file misc.h. We have already got to know some of them, for example read_string() for reading strings and print_statistics() for the output of information about the state of the memory manager.

Another frequently used function from misc.h is used_time() for measuring running times. It is used as follows: A call

float T = used_time();

without parameters returns the CPU time consumed until now. This time can be saved in a variable T for later measurings.

In order to find out at a later time how much time has passed since T, used_time() can be invoked with T as argument:

float elapsed_time = used_time(T);

The function then returns the difference between the two points in time, that is the time passed in between. In addition, it resets T to the CPU time consumed until then; thereby, calls of used_time(T) can be put in series to successively measure the times used up in individual code sections.

We demonstrate the use of used_time() by measuring the running times of individual sections in our anagram program from Section 2.3.5. This program is composed of the three partial steps reading, sorting and printing, and runs for a quite long time all in all since the number of words to be read and sorted (approximately 300,000) is quite large in our example dictionary. The function used_time() is used as follows to measure the running times of the three partial steps:

#include <LEDA/misc.h>
using leda::used_time;

// later inside main()

  // Set startTime and T to the currently used CPU time
  float startTime = used_time(); 
  float T = startTime; 

  // Read all words
  // Set T to the currently used CPU time and return the difference
  cout << "Time to read in words: " << used_time(T) << endl;
  // Sort according to user defined ordering
  cout << "Time to sort: " << used_time(T) << endl;

  // Print all sequences of equivalent words of length > 1
  cout << "Time to find all sequences of length > 1: " 
       << used_time(T) << endl;

  cout << "Total time: " << used_time(startTime) << endl;

The output of the program on the author's machine is:

Time to read in words: 7.51
Time to sort: 4.08
Time to find all sequences of length > 1: 0.4
Total time: 11.99

Further information

Some further useful functions are declared in the file misc.h. For example, there are functions for swapping two variables and for the calculation of the minimum and the maximum of two values. More information about these functions is found on the corresponding manual page.