Print runtime of code segment in C

1 min read

In C programs, sometimes it is necessary to test the running time of a specific code segment. The following code implements code runtime detection in debug mode by adding the header file “time.h” and macro definition.

#include "time.h" 
#ifdef _DEBUG_MODE_ 
	clock_t tmStart,tmEnd; 
	long mSec; 
#endif 
#ifdef _DEBUG_MODE 
  tmStart = clock(); 
#endif 
  // code segment 
#ifdef _DEBUG_MODE_ 
  tmEnd = clock(); 
  mSec = (tmEnd-tmStart) ; // CLOCKS_PER_SEC 
  printf("calculate time:%ld mSec\n",mSec); 
#endif

Tags