Write a small program to count function call time, simple and straightforward to see the code, there are three files, FunTimer.h, FunTimer.cpp, FunTimerMan.cpp are as follows:
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 One # include <iostream> #include <ctime> #include <string>using namespace Std;class funtimer{public : Funtimer (); Funtimer (String funname), ~funtimer ();p rivate: 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 One 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__) to the first sentence of the function;
Compile to see the results as follows:
Linux C + + statistical function call time