1. 使用通透比较器提升一些容器与比较有关的操作
通过示例说明对于一些容器,使用通用比较器的版本在执行与比较有关的操作时性能会由明显的提升。
std::less<void>是std::less
的特化版本,定义中含有typedef void is_transparent
。
main.cpp
#include <iostream>
#include <map>
#include <string>
#include <functional> // std::less
#include <mutex>
#include "pf_tool/profile.h"
std::mutex mu;
PROFILE_REGISTER(test1);
void test1(std::map<std::string, int>& mp) {
PROFILE_CHECK(test1);
mp.find("one");
mp.find("two");
mp.find("three");
mp.find("four");
mp.find("five");
mp.find("six");
}
PROFILE_REGISTER(test2);
void test2(std::map<std::string, int, std::less<>>& mp) {
PROFILE_CHECK(test2);
mp.find("one");
mp.find("two");
mp.find("three");
mp.find("four");
mp.find("five");
mp.find("six");
}
auto main()->int {
std::map<std::string, int> mp1;
mp1["one"] = 1;
mp1["two"] = 2;
mp1["three"] = 3;
mp1["four"] = 4;
mp1["five"] = 5;
std::map<std::string, int, std::less<>> mp2;
mp2["one"] = 1;
mp2["two"] = 2;
mp2["three"] = 3;
mp2["four"] = 4;
mp2["five"] = 5;
constexpr int kLoops = 1000000;
for (int i = 0; i < kLoops; ++i)
{
std::lock_guard<std::mutex> lg(mu);
test1(mp1);
}
for (int i = 0; i < kLoops; ++i)
{
std::lock_guard<std::mutex> lg(mu);
test2(mp2);
}
return 0;
}
其中两次的运行结果:
---> Performance details begin: <---
Attention, overhead is 30 cycles, and it is removed from average duration.
[test1, called 1000000 times, total duration cycle is 69336399, average duration cycle is 39.3364.]
[test2, called 1000000 times, total duration cycle is 31376001, average duration cycle is 1.376.]
---> Performance details end. <---
---> Performance details begin: <---
Attention, overhead is 31 cycles, and it is removed from average duration.
[test1, called 1000000 times, total duration cycle is 74294824, average duration cycle is 43.2948.]
[test2, called 1000000 times, total duration cycle is 31248916, average duration cycle is 0.248916.]
---> Performance details end. <---
由以上结果可知使用通透比较器的std::map
在执行查找、比较相关的操作时性能高出不少。
其它辅助性能测试的文件:
profile.h
#ifndef PROFILER_PROFILE_H
#define PROFILER_PROFILE_H
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <string_view>
#include <format>
#include <assert.h>
#include "profile_rdtsc.h"
#define PF_DEBUG // open performance test or not
namespace pf {
struct ProfileInfo {
int id_;
int call_count_;
uint64_t call_duration_;
std::string func_name_;
};
class Profile {
private:
Profile() {
#ifdef PF_DEBUG
constexpr int kTimes = 16;
for (int i = 0; i < kTimes; ++i) {
uint64_t begin = rdtsc_benchmark_begin();
uint64_t end = rdtsc_benchmark_end();
if (overhead_ > end - begin) {
overhead_ = end - begin; // maybe not the smallest
}
}
#endif
//std::cout << "Profile ctor called.\n";
}
~Profile() {
#ifdef PF_DEBUG
std::cout << "---> Performance details begin: <---\n";
std::cout << "Attention, overhead is " << overhead_
<< " cycles, and it is removed from average duration.\n";
for (const auto &item: info_) {
if (!item.call_count_) {
continue;
}
double average = static_cast<double>(item.call_duration_) / static_cast<double>(item.call_count_) -
static_cast<double>(overhead_);
if (average < 0) {
average = 0.0; // time cost is smaller than overhead_, because the overhead_ is not accuracy.
}
std::cout << "[" << item.func_name_ << ", called " << item.call_count_ << " times, total duration cycle is "
<< item.call_duration_ << ", average duration cycle is " << average << ".]" << std::endl;
}
std::cout << "---> Performance details end. <---\n";
#endif
}
Profile(const Profile &) = delete;
Profile &operator=(const Profile &) = delete;
public:
static Profile &getInstance();
void addInfo(int id, uint64_t duration) {
assert(id >= 0 && id < static_cast<int>(info_.size()));
++info_[id].call_count_;
info_[id].call_duration_ += duration;
}
int registerFunc(const std::string_view func_name) {
auto [iter, success] = func_name_.insert(std::string(func_name));
assert(success && "One function can only be registered once!");
int func_id = static_cast<int>(info_.size());
info_.push_back({func_id, 0, 0, *iter});
//std::cout << "registering......" << func_name << std::endl;
return func_id;
}
private:
std::set<std::string> func_name_;
std::vector<ProfileInfo> info_;
uint64_t overhead_{~0UL};
};
class ProfilingChecker {
public:
ProfilingChecker(int id) : id_(id), start_time_(rdtsc_benchmark_begin()) {
//std::cout << "ProfilingChecker ctor called.\n";
}
~ProfilingChecker() {
uint64_t end_time = rdtsc_benchmark_end();
uint64_t duration = end_time - start_time_;
Profile::getInstance().addInfo(id_, duration);
//std::cout << "ProfilingChecker dtor called.\n";
}
ProfilingChecker(const ProfilingChecker &) = delete;
ProfilingChecker &operator=(const ProfilingChecker &) = delete;
private:
int id_;
uint64_t start_time_;
};
int doProfileRegister(const std::string_view func_name);
#ifdef PF_DEBUG
#define PROFILE_REGISTER(func) static const int _pf_id_##func = pf::doProfileRegister(#func);
#define PROFILE_CHECK(func) pf::ProfilingChecker _checker(_pf_id_##func);
#else
#define PROFILE_REGISTER(func)
#define PROFILE_CHECK(func)
#endif
#ifdef _MSC_VER
#define PROFILE_NOINLINE __declspec(noinline)
#else
#define PROFILE_NOINLINE __attribute__((noinline))
#endif
}
#endif //PROFILER_PROFILE_H
profile.cpp
#include "profile.h"
#include <iostream>
namespace pf {
Profile &Profile::getInstance() {
static Profile instance;
return instance;
}
int doProfileRegister(const std::string_view func_name){
return Profile::getInstance().registerFunc(func_name);
}
}
profile_rdtsc.h
#ifndef PROFILE_PROFILE_RDTSC_H
#define PROFILE_PROFILE_RDTSC_H
#include <stdint.h> // uint64_t
#ifndef HAS_HW_RDTSC
#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64) || defined(__i386)
#define HAS_HW_RDTSC 1
#else
#define HAS_HW_RDTSC 0
#endif
#endif
#if HAS_HW_RDTSC
#ifdef _WIN32
#include <intrin.h> // __rdtsc/_mm_lfence/_mm_mfence
#elif __has_include(<x86intrin.h>)
#include <x86intrin.h> // __rdtsc/_mm_lfence/_mm_mfence
#endif
#else
#include <chrono> // std::chrono::steady_clock/nanoseconds
#endif
// Macro to forbid the compiler from reordering instructions
#ifdef _MSC_VER
#define RDTSC_MEM_BARRIER() _ReadWriteBarrier()
#else
#define RDTSC_MEM_BARRIER() __asm__ __volatile__("" : : : "memory")
#endif
inline uint64_t rdtsc()
{
RDTSC_MEM_BARRIER();
#if HAS_HW_RDTSC
uint64_t result = __rdtsc();
#else
uint64_t result = std::chrono::steady_clock::now().time_since_epoch() /
std::chrono::nanoseconds(1);
//uint64_t result = std::chrono::high_resolution_clock::now().time_since_epoch() /
// std::chrono::nanoseconds(1);
#endif
RDTSC_MEM_BARRIER();
return result;
}
#if HAS_HW_RDTSC
inline uint64_t rdtsc_benchmark_begin()
{
// memory fence, according to x86 architecture,保障开始测试之前让CPU将之前未执行完的指令执行完
_mm_mfence();
_mm_lfence();
uint64_t result = __rdtsc();
RDTSC_MEM_BARRIER();
return result;
}
inline uint64_t rdtsc_benchmark_end()
{
_mm_lfence();
uint64_t result = __rdtsc();
RDTSC_MEM_BARRIER();
return result;
}
#else
inline uint64_t rdtsc_benchmark_begin()
{
return rdtsc();
}
inline uint64_t rdtsc_benchmark_end()
{
return rdtsc();
}
#endif
#endif //PROFILE_PROFILE_RDTSC_H
2. 使用通透比较器实现往std::set
中放入自定义类型
#include <iostream>
#include <set>
#include <string>
#include <functional> // std::less
template<class IdType>
struct id_compare
{
template<class U, class V>
bool operator()(const U& lhs, const V& rhs) const {
return lhs.id_ < rhs.id_;
}
template<class U>
bool operator()(const U& lhs, const IdType& rhs_id) const {
return lhs.id_ < rhs_id;
}
template<class V>
bool operator()(const IdType& lhs_id, const V& rhs) const {
return lhs_id < rhs.id_;
}
typedef void is_transparent; // 给容器(如set)看的,没有这个编译器会报错
};
struct Obj
{
int id_;
std::string color_;
};
auto main()->int {
//std::set<Obj> s1{ {1,"red"}, {2,"blue"},{3,"green"}}; // 错误C2678,“ < ”: 没有找到接受“const _Ty”类型的左操作数的运算符(或没有可接受的转换)
std::set<Obj, id_compare<int>> s2{ {1,"red"}, {2,"blue"},{3,"green"} };
std::cout << s2.find(1)->id_ << ": " << s2.find(1)->color_ << std::endl; // 1: red
return 0;
}