一 需求:
c++11后有些让人看着很炫的语法糖,比如tuple,for_each等,但是它们并不能提升c++程序性能,做个简单测试,验证这些语法糖带来的效果。
二 实现:
1.测试函数返回多个值
(1)使用tuple返回
(2) 使用结构体引用返回
2.测试遍历一个vector,并对其中元素执行操作
(1) 使用普通循环
(2) 使用for (auto &e : v)
(3) 使用for_each和lamba表达式
三 测试代码
1.test.cpp
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
template <typename T, auto value>
T foo(T a) {
return a + value;
}
tuple<int, double, string>f() {
return make_tuple(1, 1.00, "123");
}
struct T {
int a;
double b;
string c;
};
void f(T &t) {
t.a = 1;
t.b = 1.00;
t.c = "123";
}
void f0(const vector<string>&v) {
int size = v.size();
string str;
for (int i = 0;i < size;i++) {
str = v[i];
}
}
void f1(const vector<string>&v) {
string str;
for (auto &e : v) {
str = e;
}
}
void f2(const vector<string>&v) {
string str;
for_each(begin(v), end(v), [&str] (auto e) {
str = e;
});
}
int main() {
// cout << foo<double, 10>(12.0) << endl;
T t;
vector<string>v{"123", "1212", "hello world", "c++ world", "fun work"};
for (int i = 0;i < 1000000;i++) {
// auto [x, y, z] = f(); // 0.254s
// f(t); // 0.117s
// f0(v); // 0.330s
// f1(v); // 0.368s
f2(v); // 0.792s
}
/* cout << x << endl;
cout << y << endl;
cout << z << endl;*/
return 0;
}
2.make.sh
g++ -std=c++17 -g -o Test test.cpp -pthread

本文通过对比测试,评估了C++11引入的语法糖如tuple、for_each和lambda表达式在函数返回值及vector遍历操作中的实际性能表现。
4471

被折叠的 条评论
为什么被折叠?



