标签:des class blog code tar int
写了个objectpool,很简单,就是个线程安全的队列。
#pragma once #include <iostream> #include <concurrent_vector.h> #include <concurrent_queue.h> #include <algorithm> template <typename T> class ObjectPool { public: ObjectPool(size_t chunk_size = kdefault_size, size_t chunk_num = 32) : chunk_size_ (chunk_size) , chunk_num_(chunk_num) { allocate_chunk(); } ~ObjectPool() { std::for_each(all_objects_.begin(), all_objects_.end(), ObjectPool<T>::array_delete_object); } T* acquire_object() { if (free_list_.empty()) { allocate_chunk(); } T *obj = nullptr; free_list_.try_pop(obj); return obj; } void release_object(T* obj) { if (NULL != obj) free_list_.push(obj); } protected: void allocate_chunk() { printf("%s\n", __FUNCTION__); for (int i = 0; i < chunk_num_; ++i) { T* new_objects = new T(chunk_size_); all_objects_.push_back(new_objects); free_list_.push(new_objects); } } static void array_delete_object(T* obj) { delete obj; } private: Concurrency::concurrent_queue<T*> free_list_; Concurrency::concurrent_vector<T*> all_objects_; int chunk_size_; //对象池中预分配对象个数 int chunk_num_; static const size_t kdefault_size = 100; //默认对象池大小 ObjectPool(const ObjectPool<T>& src); ObjectPool<T>& operator=(const ObjectPool<T>& rhs); };
主线程开启业务线程来写:
#define GLOG_NO_ABBREVIATED_SEVERITIES #include <windows.h> #include <glog/logging.h> #include "ThreadLog.h" #include <random> #include <chrono> #include <thread> typedef std::chrono::high_resolution_clock::time_point time_point; typedef std::chrono::duration<int64_t,std::ratio<1, 1000> > millisecond; typedef std::chrono::duration<int64_t,std::ratio<1, 1000000> > microsecond; void writeLog(void* para) { std::random_device rd; int lognum = *(int*)para; for (int i = 0; i < lognum; ++i){ LOG(INFO) << "how are " << rd() << " cookies"; } } using namespace google; int main(int argc, char* argv[]) { auto start_time = std::chrono::high_resolution_clock::now(); google::InitGoogleLogging("test/testsss"); google::base::Logger* mylogger = new google::ThreadLog; SetLogger(google::GLOG_INFO, mylogger); google::SetLogDestination(google::GLOG_INFO, "../Debug/Debug"); int num_cookies = 0; int lognum = 1000000; int threadNum = 1; std::thread* threads = new std::thread[threadNum]; for (int i = 0; i < threadNum; ++i) { threads[i] = std::thread(writeLog, &lognum); } for (int i = 0; i < threadNum; ++i) { threads[i].join(); } auto application_end_time = std::chrono::high_resolution_clock::now(); auto application_time_us = std::chrono::duration_cast<microsecond>(application_end_time - start_time).count()/1000; LOG(INFO) << "threadglog total use " << application_time_us << "s"; google::ShutdownGoogleLogging(); }
单线程投递写日志一百万条用了13046s;
10个线程每个线程写一万条use 7808s;
额,忘记了,用的机子是thinkpad E431,四核 4G内存,显然还是发回来多核的优势。
改进Threadglog并增加多线程写测试,布布扣,bubuko.com
标签:des class blog code tar int
原文地址:http://blog.csdn.net/boyxiaolong/article/details/24911515