编程语言

img rabbit2003

一个高效的C++性能计数器模板

发表于2004/9/26 15:35:00  1336人阅读

分类: VC/C++

一个高效的C++性能计数器模板

email: larrin2002@msn.com

homepage: www.larrin.net

摘要:对性能期望较高的系统中,简单高效的性能计数器对发现系统中的性能瓶颈很有价值。本文给出一个使用简单但高效的C++性能计数器模板。本文给出的计数器是Windows版本的,但移植到Linux下非常简单。

计数器代码如下:

//PerformanceCounter.h

#ifndef _LARRINSDK_PERFORMANCE_COUNTER_H_
#define _LARRINSDK_PERFORMANCE_COUNTER_H_

#include "LarrinSdk.h"
#include <iostream>
#include <windows.h>

using namespace std;

BEGIN_LARRIN_SDK

template<class T>
class CPerformanceCounter
{
 const char  *m_Name ;
 unsigned long m_tmpCounter ;
 unsigned long m_TickCounter;

 CPerformanceCounter(const char *name):m_Name(name),m_TickCounter(0)
 {
 }

public:

 ~CPerformanceCounter()
 {
  cout << "PerformanceCounter " << m_Name << " : " << m_TickCounter << endl ;
 }

 static CPerformanceCounter & getInstance(const char *name)
 {
  static CPerformanceCounter instance(name);
  return instance ;
 }

 void BeginCounter()
 {
  m_tmpCounter = GetTickCount();
 }

 void EndCounter()
 {
  m_TickCounter += (GetTickCount() - m_tmpCounter) ;
 }
};

template <class T>
class CPerformanceCounterHelper
{
 const char *m_name ;
public:
 CPerformanceCounterHelper(const char *counter_name):m_name(counter_name)
 {
  CPerformanceCounter<T>::getInstance(m_name).BeginCounter();
 }

 ~CPerformanceCounterHelper()
 {
  CPerformanceCounter<T>::getInstance(m_name).EndCounter();
 }
};

#define DEFINE_COUNTER(x) struct x;

#ifdef ENABLE_PERFORMANCE_COUNTER
#define BEGIN_COUNTER(counter_name) CPerformanceCounter<counter_name>::getInstance(#counter_name).BeginCounter();
#define END_COUNTER(counter_name) CPerformanceCounter<counter_name>::getInstance(#counter_name).EndCounter();
#define COUNTER_HELPER(counter_name) CPerformanceCounterHelper<counter_name> counter_##counter_name(#counter_name);
#else
#define BEGIN_COUNTER(counter_name)
#define END_COUNTER(counter_name)
#endif

END_LARRIN_SDK

#endif //_LARRINSDK_PERFORMANCE_COUNTER_H_

 

测试程序:

1.main.cpp

#include "PerformanceCounter.h"

extern void test1();

using namespace LarrinSdk;

DEFINE_COUNTER(counter_1)

void main()
{
 {
  COUNTER_HELPER(counter_1)
  for(int i = 0 ; i < 300 ; i++)
  {
   Sleep(1);
  }
 }

 test1();
}

//2.test1.cpp

#include "PerformanceCounter.h"

using namespace LarrinSdk;

DEFINE_COUNTER(counter_1)

void test1()
{
 BEGIN_COUNTER(counter_1)
 for(int i = 0 ; i < 1000 ; i++)
 {
  Sleep(1);
 }
 END_COUNTER(counter_1)
}

阅读全文
0 0

相关文章推荐

img
取 消
img