没有废话,直接上测试代码
#include <chrono>
#include <string>
#include <iostream>
#include <functional>
using namespace std;
using namespace chrono;
static uint64_t size = 12550820;
static string test_str(size, 'S');
uint64_t test(function<void()>& target) {
auto time_begin = system_clock::now();
target();
auto time_end = system_clock::now();
return static_cast<uint64_t>(duration_cast<microseconds>(time_end - time_begin).count());
}
int main() {
std::function<void()> for_f = []()->void{
uint64_t test = 0;
for(char mychar : test_str) {
test++;
}
};
std::function<void()> normal_iterator_f = []()->void{
uint64_t test = 0;
for(auto i = test_str.begin(); i != test_str.end(); i++) {
test++;
}
};
std::function<void()> reverse_iterator_f = []()->void{
uint64_t test = 0;
for(auto i = test_str.rbegin(); i != test_str.rend(); i++) {
test++;
}
};
std::function<void()> const_iterator_f = []()->void{
uint64_t test = 0;
for(string::const_iterator i = test_str.begin(); i != test_str.end(); i++) {
test++;
}
};
std::function<void()> normal_cstyle_f = []()->void{
uint64_t test = 0;
char* char_ptr = const_cast<char*>(test_str.c_str());
for(uint64_t i = 0; i < test_str.size(); i++) {
char_ptr++;
test++;
}
};
std::function<void()> reverse_cstyle_f = []()->void{
uint64_t test = 0;
char* char_ptr = const_cast<char*>(test_str.c_str());
char_ptr += test_str.size();
for(uint64_t i = 0; i < test_str.size(); i++) {
char_ptr--;
test++;
}
};
std::function<void()> index_f = []()->void{
uint64_t test = 0;
char mychar;
for(uint64_t i = 0; i < test_str.size(); i++) {
test++;
mychar = test_str[i];
}
};
cout << "(单位:毫秒)" << endl;
cout << "标准for遍历用时 \t" << test(for_f) << endl;
cout << "标准iterator用时 \t" << test(normal_iterator_f) << endl;
cout << "反向iterator用时 \t" << test(reverse_iterator_f) << endl;
cout << "常量iterator用时 \t" << test(const_iterator_f) << endl;
cout << "标准C风格遍历用时 \t" << test(normal_cstyle_f) << endl;
cout << "反向C风格遍历用时 \t" << test(reverse_cstyle_f) << endl;
cout << "下标访问用时 \t" << test(index_f) << endl;
return 0;
}
运行结果
~/build $ g++
~/app/potato/worldbox/util/speedtest.cc
~/build $ ./a.out
(单位:毫秒)
标准for遍历用时 475926
标准iterator用时 1530713
反向iterator用时 1503410
常量iterator用时 1529692
标准C风格遍历用时 537057
反向C风格遍历用时 536231
下标访问用时 1058003
~/build $