In project development, in order to improve the efficiency of the program, it is first to locate the part of the code that takes a long time, and then improves the code--to shorten the execution time. This takes a time to get the function to get the time accurately, in the Linux/unix system has the corresponding time to get the function, but to its conversion encapsulation can get the values we want to understand, the following example is to encapsulate the gettimeofday () function and struct The time acquisition function acquired by the TIMEVAL structure.
#include <sys/time.h> #include <unistd.h>
define functions: int gettimeofday (struct timeval * TV, struct timezone * tz);
function Description: Gettimeofday () will return the current time to the structure that the TV refers to, and the local time zone information is placed in the structure that TZ refers to.
the TIMEVAL structure is defined as:
struct timeval{
long tv_sec; Seconds
long tv_usec; Microseconds
};
The TIMEZONE structure is defined as:
struct TimeZone
{
int tz_minuteswest; How many minutes is the difference with Greenwich?
int tz_dsttime; The state of daylight saving time
};
many times do not have a second parameter value, so it is generally set to ' NULL'
The return value is a subtle unit
UB8 Ldw_time ()
{
UB8 TM;
struct Timeval TV;
Gettimeofday (&TV, NULL);
TM = tv.tv_sec * 1000000 + tv.tv_usec;
return TM;
}
The encapsulated time acquisition function can also be defined with a macro, which is processed at preprocessing and is highly efficient in code execution
#define START_TIME (_st) _st = Ldw_time ();
#definie end_time (_et) _et = Ldw_time ();
#defime Waste_time (_st,_et) (_et-_st)
int main (int argc,char *argv[])
{
Long t1= 0;
Long t2 = 0;
Char buf[1*1024*1024];
T1 = Ldw_time ();
Start_time (t1);
memset (buf,0,sizeof (BUF));
T2 = Ldw_time ();
End_time (T2);
printf ("Memset time:%ul\n", t2-t1);
printf ("Memset time:%ul\n", Waste_time (T1,T2));
return 0;
}
Time acquisition function Encapsulation--linux/unix