Linux c ++ statistics function call time, linux Function
Write a small program to count the function call time. The code is simple and clear. There are three files: FunTimer. h, FunTimer. cpp, and FunTimerMan. cpp:
FunTimer. h file
# Ifndef _ FUNTIMER_H # define _ FUNTIMER_H # include <iostream> # include <sys/time. h ># include <string> using namespace std; class FunTimer {public: FunTimer (); FunTimer (string funName );~ FunTimer (); private: string funName; timeval _ start; timeval _ end ;}; /** method 1 # include <iostream> # include <ctime> # include <string> using namespace std; class FunTimer {public: FunTimer (); FunTimer (string funName );~ FunTimer (); private: string funName; clock_t _ start; clock_t _ end;}; */# endif
FunTimer. cpp File
# Include "FunTimer. h "FunTimer: FunTimer () {gettimeofday (& _ start, NULL);} FunTimer: FunTimer (string funName) {this-> funName = funName; gettimeofday (& _ start, NULL);} FunTimer ::~ FunTimer () {gettimeofday (& _ end, NULL); float timeuse = 1000000 * (_ end. TV _sec-_ start. TV _sec) + (_ end. TV _usec-_ start. TV _usec); timeuse/= 1000000; cout <endl; cout <this-> funName <":" <timeuse <endl;}/** method 1 FunTimer:: FunTimer () {_ start = clock ();} FunTimer: FunTimer (string funName) {this-> funName = funName; _ start = clock ();} FunTimer :: ~ FunTimer () {_ end = clock (); cout <this-> funName <(double) (_ end-_ start)/CLOCKS_PER_SEC <endl ;}*/
FunTimerMain. cpp file for testing
#include <iostream>#include "FunTimer.h"using namespace std;void testPrintFun(){FunTimer mFunTimer(__FUNCTION__); for(int i=0;i<1000;i++) { cout<<" "; }}void testPrintFun2(){ FunTimer mFunTimer(__FUNCTION__); for(int i=0;i<2000;i++) { cout<<" "; }}int main(int argc, char* argv[]){FunTimer mFunTimer(__FUNCTION__);testPrintFun();testPrintFun2();/**clock_t start = clock(); testPrintFun();clock_t end = clock(); cout<<endl; cout<<(end-start)<<endl; */ return 0;}
Test method: Add FunTimer mFunTimer (_ FUNCTION _) In the first sentence of the FUNCTION.
The compilation result is as follows: