在程序优化期间,尝试优化迭代遍历向量的循环,我发现以下事实::: std :: vector :: at()比operator []快得多!
在发布和调试版本(VS2008 x86)中,operator []比at()快5到10倍.
在网上读了一下让我意识到at()有边界检查.好的,但是,将操作放慢了10倍?!
有什么理由吗?我的意思是,边界检查是一个简单的数字比较,还是我错过了什么?
问题是这种性能受损的真正原因是什么?
更进一步,有没有办法让它更快?
我肯定会在其他代码部分(我已经有自定义边界检查!)中将所有at()调用与[]交换.
概念证明:
#define _WIN32_WINNT 0x0400
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <conio.h>
#include <vector>
#define ELEMENTS_IN_VECTOR 1000000
int main()
{
__int64 freq, start, end, diff_Result;
if(!::QueryPerformanceFrequency((LARGE_INTEGER*)&freq))
throw "Not supported!";
freq /= 1000000; // microseconds!
::std::vector<int> vec;
vec.reserve(ELEMENTS_IN_VECTOR);
for(int i = 0; i < ELEMENTS_IN_VECTOR; i++)
vec.push_back(i);
int xyz = 0;
printf("Press any key to start!");
_getch();
printf(" Running speed test..\n");
{ // at() …Run Code Online (Sandbox Code Playgroud) 使用stl :: vector:
vector<int> v(1);
v[0]=1; // No bounds checking
v.at(0)=1; // Bounds checking
Run Code Online (Sandbox Code Playgroud)
有没有一种方法来禁用边界检查,而不必重写所有at()的[]?我正在使用GNU标准C++库.
编辑:我改变了at()对[]在我怀疑的瓶颈区域,并显著减少了计算时间.但是,由于我在开发代码和运行实验之间进行迭代,我想在开发过程中启用边界检查,并在运行实验时禁用它.我想安德鲁的建议是最好的解决方案.
为了给函数提供修改向量的选项,我不能这样做
curr = myvec.at( i );
doThis( curr );
doThat( curr );
doStuffWith( curr );
Run Code Online (Sandbox Code Playgroud)
但我必须这样做:
doThis( myvec.at( i ) );
doThat( myvec.at( i ) );
doStuffWith( myvec.at( i ) );
Run Code Online (Sandbox Code Playgroud)
(正如我的另一个问题的答案所指出的那样)
myvec.at()那时我打算打个电话.与使用变量存储结果的第一个示例相比,它有多快?
我有不同的选择吗?我可以以某种方式使用指针吗?
当它变得严重时,myvec.at()每秒会有数千个呼叫.所以每个小表现都很重要.
std::optional 可以使用语法来访问其值,类似于普通指针一样。
std::optional<string> some_str;
if (some_str)
(*some_str).c_str();
Run Code Online (Sandbox Code Playgroud)
但它也有两个功能,has_value()并value()提供访问其价值和检查,如果该值存在。
std::optional<string> some_str;
if (some_str.has_value())
some_str.value().c_str();
Run Code Online (Sandbox Code Playgroud)
我想知道这两者之间有什么区别?
1.更冗长
2.性能?
3.更好的日志记录和调试?value()会抛出异常。
So i have this queue
deque<int> deq1(2,10);
Run Code Online (Sandbox Code Playgroud)
I Have accessed the element using 2 way and both of them return the same value
cout<<deq1[0];
cout<<deq1.at(0);
Run Code Online (Sandbox Code Playgroud)
why did them make a special function to do the same thing or is one way better than the other?
c++ ×6
vector ×3
stl ×2
c++17 ×1
g++ ×1
libstdc++ ×1
performance ×1
stdoptional ×1
stdvector ×1
visual-c++ ×1