Registers are special storage areas within the computer's central processing unit. The actual arithmetic and logical operations that comprise a program are carried out within these registers.Normally, these operations are carried out by transferring information from the computer's memory to these registers, carrying out the indicated operations, and then transferring the results back to the computer's memory. This general procedure is repeated many times during the course of a program's execution.
The register and automatic storage classes are closely related.In particular, their visibility (i.e. their scope) is the same. Thus, register variables, like automatic variables, are local to the function in which they are declared. Furthermore, the rules governing the use of register variables are the same as those for automatic variables, except that the address operator(&) cannot be applied to register variables.
The program presented below is a variation of that shown in Section 6.4, for generating a series of Fibonacci numbers.
/* calculate the first 23 Fibonacci numbers 10,000,000 times, to illustrate the use of register variables*/
#include < stdio.h >
#include < time.h >
long int fibonacci (int count);
main()
{
time_t start, finish; /* start and finish times*/
int count, n=23;
long int loop, loopmax = 1000000;
register int f , f1, f2;
/* tag the starting time*/
time(&start);
/* do multiple loops*/
for (loop=1; loop <= loopmax; ++loop) {
f1=1;
f2=1;
/*generate the first n Fibonacci numbers*/
for (count=1;count <= n;++count) {
f= (count < 3)? 1 : f1+f2;
f2=f1;
f1=f;}
}
/* adjust the counter and tag the completion time*/
--count;
time(&finish);
/*display the output*/
printf ("i= %d F= %d\n", count, f);
printf ("elapsed time: %0.1f seconds", difftime (finish, start));}
The variables start and finish are of type time_t, as defined in the header file time.h.The program also makes use of the library function difftime, which returns the time difference defined by the variables finish and start.
When executed on a Pentium-class desktop computer, the following results were obtained:
i=23 F=28657
elapsed time: 37 seconds
No comments:
Post a Comment