thread_usage.h
#ifndef __THREAD_USAGE__
#define __THREAD_USAGE__
#include <fstream>
#include <string>
#include <map>
#include <pthread.h>
#include <sys/time.h>
namespace thread
{
class CThreadUsage
{
public:
CThreadUsage(unsigned int printCount, std::string strFilename);
~CThreadUsage();
void AddThread(pthread_t pthread_id);
void Add();
private:
std::map<pthread_t, int> usage_;
unsigned int printCount_;
std::ofstream output_;
unsigned int count_;
pthread_mutex_t mutex_;
timeval tstart_;
timeval tend_;
void Print();
void Clear();
};
}
#endif //__THREAD_USAGE__
thread_usage.cpp
#include "thread_usage.h"
using namespace thread;
CThreadUsage::CThreadUsage(unsigned int printCount, std::string strFilename)
:printCount_(printCount),
output_(strFilename.c_str()),
count_(0)
{
pthread_mutex_init(&mutex_, NULL);
}
CThreadUsage::~CThreadUsage()
{
output_.close();
pthread_mutex_destroy(&mutex_);
}
void CThreadUsage::AddThread(pthread_t pthread_id)
{
pthread_mutex_lock(&mutex_);
usage_.insert(std::make_pair<pthread_t, int>(pthread_id, 0));//将每个线程的线程ID加入map.
pthread_mutex_unlock(&mutex_);
}
void CThreadUsage::Add()
{
pthread_mutex_lock(&mutex_);
++usage_[pthread_self()];
++count_;
if (1 == count_)
{
gettimeofday(&tstart_, NULL);
}
else if (printCount_ == count_)
{
gettimeofday(&tend_, NULL);
Print();//打印
Clear();//清空
}
pthread_mutex_unlock(&mutex_);
}
void CThreadUsage::Print()
{
double linStart = ((double)tstart_.tv_sec * 1000000 + (double)tstart_.tv_usec); //unit S
double linEnd = ((double)tend_.tv_sec * 1000000 + (double)tend_.tv_usec); //unit S
double delta = (linEnd-linStart)/1000; //Micro S
output_ << "========== Begin ========" << "\n"
<< "Total take: " << delta << " ms, avarage " << delta/printCount_ << "ms per.\n"
<< "Thread_ID\t" << "Usage" << std::endl;
for (std::map<pthread_t, int>::iterator iBegin = usage_.begin();
iBegin != usage_.end(); ++iBegin)
{
output_ << iBegin->first << "\t" << iBegin->second << std::endl;
}
output_ << "=========== End =========" << std::endl;
}
void CThreadUsage::Clear()
{
count_ = 0;
for (std::map<pthread_t, int>::iterator iBegin = usage_.begin();
iBegin != usage_.end(); ++iBegin)
{
iBegin->second = 0;
}
}
测试函数:
#include "thread_usage.h"
thread::CThreadUsage oThreadUsage(100, "num.txt");//每处理完100个线程,就打印一次每个线程处理的任务数量
void* pthread_func(void* argv)
{
pthread_detach(pthread_self());
oThreadUsage.AddThread(pthread_self());
while (1)
{
oThreadUsage.Add();
sleep(1);
}
return NULL;
}
int main()
{
pthread_t thread[10];
for (int iIndex = 0; iIndex < 10; ++iIndex)
{
pthread_create(&thread[iIndex], NULL, pthread_func, NULL);
}
while(1);
}