Sams Teach Yourself C in 21 Days

(singke) #1
Exploring the C Function Library 541

19


%z The locale’s time zone or abbreviation. If the time zone isn’t known, then this
would be blank.
%Z The time zone name if the information is available or blank if not.
%% A single percent sign %.

Calculating Time Differences
You can calculate the difference, in seconds, between two times with thedifftime()
macro, which subtracts two time_tvalues and returns the difference. The prototype is
double difftime(time_t later, time_t earlier);
This function subtracts earlierfromlaterand returns the difference, the number of
seconds between the two times. A common use of difftime()is to calculate elapsed
time, as demonstrated (along with other time operations) in Listing 19.2.
You can determine duration of a different sort using theclock()function, which returns
the amount of time that has passed since the program started execution, in 1/100-second
units. The prototype is
clock_t clock(void);
To determine the duration of some portion of a program, call clock()twice—before and
after the process occurs—and subtract the two return values.

Using the Time Functions ............................................................................


Listing 19.2 demonstrates how to use the C library time functions.

LISTING19.2 times.c. Using the C library time functions
1: /* Demonstrates the time functions. */
2:
3: #include <stdio.h>
4: #include <time.h>
5:
6: int main( void )
7: {
8: time_t start, finish, now;
9: struct tm *ptr;
10: char *c, buf1[80];
11: double duration;
12:

TABLE19.1 continued
Specifier What It’s Replaced By

INPUT

30 448201x-CH19 8/13/02 11:20 AM Page 541

Free download pdf