提问人:Joeger-Bahar 提问时间:3/25/2023 更新时间:3/25/2023 访问量:94
通过引用传递基元类型 C++
Passing primitive type by reference C++
问:
我发现很多人说,按值传递原始值(例如 int)比按引用传递要快。
但是,我写了下面的代码,并按值传递,它的平均运行时间为 2 秒。
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
int func(unsigned long long x) {
++x;
return x;
}
int main()
{
for (int b = 0; b < 5; b++) {
unsigned long long x = 0;
auto start = high_resolution_clock::now();
for (long long j = 0; j < 500000; j++) {
for (long long i = 0; i < 180000000; i++) {
x = func(x);
}
}
auto stop = high_resolution_clock::now();
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cout << x <<" iterations took " << microseconds << " microseconds\n";
}
}
然后,当我通过引用时,它的平均时间不到 1 微秒。
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
void func(unsigned long long& x) {
++x;
}
int main()
{
for (int b = 0; b < 5; b++) {
unsigned long long x = 0;
auto start = high_resolution_clock::now();
for (long long j = 0; j < 500000; j++) {
for (long long i = 0; i < 180000000; i++) {
func(x);
}
}
auto stop = high_resolution_clock::now();
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cout << x <<" Took " << microseconds << " microseconds\n";
}
}
我想解释为什么会发生这种情况。
免责声明:我对C++相当陌生
答: 暂无答案
评论
unsigned long long
uint64_t
-O3