測試vector、list、set調用empty和size的耗時是否爲常數

      在閱讀代碼時,發現有使用size()==0判斷是否容器爲空的,而從<<Effective STL>>上看到size()不能保證常數時間,建議使用empty()替換。因此我做了一個實驗,發現size()並不能保證常數時間,但empty可以保證。


/**
    測試vector、list、set調用empty和size的耗時是否爲常數,
    結論:empty()的調用時間都是常數,list的size()的調用時間非常數
    使用建議:判斷成員是否爲空時使用empty(),而非size() == 0

    input   COUNT:100000(10W) 1000000(100W)

    output
            member count is:1000000
            test vector.empty():
            cost time(ms):0
            test vector.size():
            cost time(ms):0
            ---------------------
            test list.empty():
            cost time(ms):0
            test list.size():
            cost time(ms):8
            ---------------------
            test set.empty():
            cost time(ms):0
            test set.size():
            cost time(ms):0
            ---------------------

            member count is:10000000
            test vector.empty():
            cost time(ms):0
            test vector.size():
            cost time(ms):0
            ---------------------
            test list.empty():
            cost time(ms):0
            test list.size():
            cost time(ms):79
            ---------------------
            test set.empty():
            cost time(ms):0
            test set.size():
            cost time(ms):0
            ---------------------
 */

#include <iostream>
#include <vector>
#include <set>
#include <list>
#include <sys/time.h>
using namespace std;
typedef unsigned long long ull;

#define COST_TIME_START \
{\
    timeval start; \
    gettimeofday(&start, NULL);

#define COST_TIME_END \
    timeval end;\
    gettimeofday(&end, NULL); \
    cout << "cost time(ms):" << ((end.tv_sec*1000 + end.tv_usec/1000) - (start.tv_sec*1000 + start.tv_usec/1000)) << endl; \
}


int main (int argc, char **argv) {

    cout << "member count is:" << COUNT << endl;

    vector<ull> v;
    v.assign(COUNT, 0);
    cout << "test vector.empty():" << endl;
    COST_TIME_START
        v.empty();
    COST_TIME_END

    cout << "test vector.size():" << endl;
    COST_TIME_START
        v.size();
    COST_TIME_END
    cout << "---------------------" << endl;

    list<ull> l;
    l.assign(COUNT, 0);

    cout << "test list.empty():" << endl;
    COST_TIME_START;
        l.empty();
    COST_TIME_END;

    cout << "test list.size():" << endl;
    COST_TIME_START;
        l.size();
    COST_TIME_END;
    cout << "---------------------" << endl;


    set<ull> s;
    for (ull i = 0; i < COUNT; ++i) {
        s.insert(i);
    }

    cout << "test set.empty():" << endl;
    COST_TIME_START
        s.empty();
    COST_TIME_END

    cout << "test set.size():" << endl;
    COST_TIME_START
        s.size();
    COST_TIME_END
    cout << "---------------------" << endl;

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章