Recently, it was suddenly necessary to test the running time of each function in C language. So I searched and found that there were four methods to calculate the running time. They are implemented using clock, times, gettimeofday, and getrusage respectively. Next we will introduce them one by one and compare their advantages and disadvantages. System test environment: VirtualBox (Ubuntu9.10) gccversion4.4.1libc62.10.1-0ubuntu16Core
Recently, it was suddenly necessary to test the running time of each function in C language. So I searched and found that there were four methods to calculate the running time.
They are implemented using clock, times, gettimeofday, and getrusage respectively. Next we will introduce them one by one and compare their advantages and disadvantages.
System test environment:
VirtualBox (Ubuntu 9.10)
Gcc version 4.4.1
Libc6 2.10.1-0ubuntu16
Core Duo T2500 2 GMHz
First, paste the program for testing.
The process done by the program is very simple, that is, to fill in a matrix of 1024*1024.
You only need to modify the definition value of row 11th to use different measurement methods.
# Include
# Include
# Include
# Include
# Include
# Define TEST_BY_CLOCK (char) (0x00)
# Define TEST_BY_TIMES (char) (0x01)
# Define TEST_BY_GETTIMEOFDAY (char) (0x02)
# Define TEST_BY_GETRUSAGE (char) (0x03)
# Define TEST_METHOD (TEST_BY_GETTIMEOFDAY)
# Define COORDINATION_X (int) (1024)
# Define COORDINATION_Y (int) (1024)
Static int g_Matrix [COORDINATION_X] [COORDINATION_Y];
Double getTimeval ()
{
Struct rusage stRusage;
Struct timeval stTimeval;
If (TEST_METHOD = TEST_BY_GETTIMEOFDAY ){
Gettimeofday (& stTimeval, NULL );
} Else if (TEST_METHOD = TEST_BY_GETRUSAGE ){
Getrusage (RUSAGE_SELF, & stRusage );
StTimeval = stRusage.ru _ utime;
}
Return stTimeval. TV _sec + (double) stTimeval. TV _usec * 1E-6;
}
Int main ()
{
Int I, j;
Int n = 0;
Clock_t clockT1, clockT2;
Double doubleT1, doubleT2;
If (TEST_METHOD = TEST_BY_CLOCK ){
ClockT1 = clock ();
} Else if (TEST_METHOD = TEST_BY_TIMES ){
Times (& clockT1 );
} Else if (TEST_METHOD = TEST_BY_GETTIMEOFDAY ){
DoubleT1 = getTimeval ();
} Else if (TEST_METHOD = TEST_BY_GETRUSAGE ){
DoubleT1 = getTimeval ();
}
For (I = 0; I <COORDINATION_X; I ++ ){
For (j = 0; j <COORDINATION_Y; j ++ ){
G_Matrix [I] [j] = I * j;
}
}
If (TEST_METHOD = TEST_BY_CLOCK ){
ClockT2 = clock ();
Printf ("Time result tested by clock = % 10.30f \ n ",
(Double) (clockT2-clockT1)/CLOCKS_PER_SEC );
} Else if (TEST_METHOD = TEST_BY_TIMES ){
Times (& clockT2 );
Printf ("Time result tested by times = % 10.30f \ n ",
(Double) (clockT2-clockT1)/sysconf (_ SC _CLK_TCK ));
} Else if (TEST_METHOD = TEST_BY_GETTIMEOFDAY ){
DoubleT2 = getTimeval ();
Printf ("Time result tested by gettimeofday = % 10.30f \ n ",
(Double) (doubleT2-doubleT1 ));
} Else if (TEST_METHOD = TEST_BY_GETRUSAGE ){
DoubleT2 = getTimeval ();
Printf ("Time result tested by getrusage = % 10.70f \ n ",
(Double) (doubleT2-doubleT1 ));
}
Return 0;
}