3 回答
TA贡献1859条经验 获得超6个赞
++ii++.]
i
ii++++ioperator++
Foo& Foo::operator++() // called for ++i{
this->data += 1;
return *this;}Foo Foo::operator++(int ignored_dummy_value) // called for i++{
Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler
++(*this);
return tmp;}operator++tmp
TA贡献1817条经验 获得超14个赞
struct C{
C& operator++(); // prefix
C operator++(int); // postfixprivate:
int i_;};C& C::operator++(){
++i_;
return *this; // self, no copy created}C C::operator++(int ignored_dummy_value){
C t(*this);
++(*this);
return t; // return a copy}TA贡献1829条经验 获得超13个赞
// a.cc#include <ctime>#include <array>class Something {public:
Something& operator++();
Something operator++(int);private:
std::array<int,PACKET_SIZE> data;};int main () {
Something s;
for (int i=0; i<1024*1024*30; ++i) ++s; // warm up
std::clock_t a = clock();
for (int i=0; i<1024*1024*30; ++i) ++s;
a = clock() - a;
for (int i=0; i<1024*1024*30; ++i) s++; // warm up
std::clock_t b = clock();
for (int i=0; i<1024*1024*30; ++i) s++;
b = clock() - b;
std::cout << "a=" << (a/double(CLOCKS_PER_SEC))
<< ", b=" << (b/double(CLOCKS_PER_SEC)) << '\n';
return 0;}O(N)增量
试验
// b.cc#include <array>class Something {public:
Something& operator++();
Something operator++(int);private:
std::array<int,PACKET_SIZE> data;};Something& Something::operator++(){
for (auto it=data.begin(), end=data.end(); it!=end; ++it)
++*it;
return *this;}Something Something::operator++(int){
Something ret = *this;
++*this;
return ret;}结果
Flags (--std=c++0x) ++i i++-DPACKET_SIZE=50 -O1 1.70 2.39-DPACKET_SIZE=50 -O3 0.59 1.00-DPACKET_SIZE=500 -O1 10.51 13.28-DPACKET_SIZE=500 -O3 4.28 6.82
O(1)增量
试验
// c.cc#include <array>class Something {public:
Something& operator++();
Something operator++(int);private:
std::array<int,PACKET_SIZE> data;};Something& Something::operator++(){
return *this;}Something Something::operator++(int){
Something ret = *this;
++*this;
return ret;}结果
Flags (--std=c++0x) ++i i++-DPACKET_SIZE=50 -O1 0.05 0.74-DPACKET_SIZE=50 -O3 0.08 0.97-DPACKET_SIZE=500 -O1 0.05 2.79-DPACKET_SIZE=500 -O3 0.08 2.18-DPACKET_SIZE=5000 -O3 0.07 21.90
结语
性能方面
语义层面
i++说 increment i, I am interested in the previous value, though.++i说 increment i, I am interested in the current value或 increment i, no interest in the previous value..再说一遍,你会习惯的,即使你现在还不习惯。
克努斯。
- 3 回答
- 0 关注
- 849 浏览
添加回答
举报
