安装gperftools
下载代码
git clone https://github.com/gperftools/gperftools
cd gperftools
./autogen.sh
./configure
make -j8
sudo make install
安装
git clone git://git.sv.gnu.org/libunwind.git
cd libunwind
./configure
make
make install
代码中加入profiler函数进行cpu性能分析
#include <list>
#include <iostream>
#include <algorithm>
#include <string>
#include <google/profiler.h>
extern "C" {
#include <ctype.h>
#include <string.h>
}
template <typename T>
class HashTable {
private:
std::list< std::pair<std::string, T> >* ht;
static const int dict_hash_function_seed = 5381;
int size;
public:
HashTable(int s)
: size(s)
{
ht = new std::list< std::pair<std::string, T> >[size];
}
/* And a caseinsensitive hash function (based on djb hash) */
//来源于Redis
unsigned int dictGenCaseHashFunction(const std::string& key) {
const char* buf = key.c_str();
int len = key.length();
unsigned int hash = (unsigned int)dict_hash_function_seed;
while (len--)
hash = ((hash << 5) + hash) +(tolower(*buf++)); /* hash * 33 + c */
return hash % size;
}
bool hash(const std::string &key, const T& t) {
auto slot = &ht[dictGenCaseHashFunction(key)];
for(auto it = slot->begin(); it != slot->end(); it++) {
if(key == it->first) {
it->second = t;
return true;
}
}
slot->push_back(std::pair<std::string, T>(key, t));
return true;
//std::cout<<ht[slotPos].size()<<std::endl;
}
bool get(const std::string& key, T& t) {
auto slot = &ht[dictGenCaseHashFunction(key)];
auto it = slot->begin();
for(it = slot->begin(); it != slot->end(); it++) {
if(key == it->first) {
t = it->second;
std::cout<<t<<std::endl;
return true;
}
}
return false;
}
bool remove(const std::string& key) {
auto slot = &ht[dictGenCaseHashFunction(key)];
auto it = slot->begin();
for(it = slot->begin(); it != slot->end(); it++) {
if(key == it->first) {
//std::cout<<it->second<<std::endl;
return true;
}
}
return false;
}
};
int main(int argc, const char** argv) {
HashTable<int> hashTable(1000000);
for(int i = 0; i < 10000000; i++) {
if(i%2 == 0) {
continue;
}
std::string key = std::to_string(i);
hashTable.hash(key, i*10);
}
ProfilerStart("profiler");
for(int i = 8999999; i < 10000000; i++) {
std::string key = std::to_string(i);
int a = 0;
hashTable.get(key, a);
}
ProfilerStop();
int a = 0;
hashTable.get("127", a);
hashTable.hash("127", 127);
hashTable.get("127", a);
return 0;
}
编译并运行
g++ -o hashTable hashTable.cpp -lprofiler
./hashTable
分析
pprof --gif ./hashTable profiler > profiler.gif
点击查看图片即可看到各个函数的耗时时间统计和调用流程
优化
可以看到最耗时的是字符串的操作,特别是比较上,针对字符串比较耗时本身我们没有特别好的优化方法,不过换一个方向来说我们可以通过减少比较的次数来优化,增加hashtable的size可以使得每个slot里面的元素更少,用空间来换时间,当然这会增加我们初始化hashtable的时间。增加构造函数的hashtable为原来的10倍,再进行一次测量,结果如下:
可以看到时间上优化了接近300毫秒,优化了1/2的时间,而且大部分时间消耗在了to_string函数上面了。