Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

比较类的静态数据成员和普通数据成员哪个访问得快一点

代码

顺序访问

#include <iostream>
#include <fstream>
#include <vector>
#include <chrono>

using namespace std;
typedef chrono::microseconds UnitType;
chrono::_V2::system_clock::time_point t_start, t_end;
UnitType d;
#define TIMING_START t_start = chrono::system_clock::now();
#define TIMING_END(str)                                   \
    t_end = chrono::system_clock::now();                  \
    d = chrono::duration_cast<UnitType>(t_end - t_start); \
    cout << str << d.count() << " us" << endl;

class A
{
public:
    vector<int> nbrs;

    A(size_t sz) : nbrs(sz) {}
    void seq_access(int round, ostream &absorb_stdout)
    {
        int total = 0;
        for (int i = 0; i < round; ++i)
            for (size_t j = 0, jed = nbrs.size(); j < jed; ++j)
                total += nbrs[j];
        absorb_stdout << total;
    }
};
class B
{
public:
    static vector<int> nbrs;

    void seq_access(int round, ostream &absorb_stdout)
    {
        int total = 0;
        for (int i = 0; i < round; ++i)
            for (size_t j = 0, jed = nbrs.size(); j < jed; ++j)
                total += nbrs[j];
        absorb_stdout << total;
    }
};
vector<int> B::nbrs;
void compare_static_data_member(ostream &absorb_stdout)
{
    const size_t sz = 100000000;
    int repeat_times = 30;
    B::nbrs.resize(sz);
    B b;
    A a(sz);

    TIMING_START
    a.seq_access(repeat_times, absorb_stdout);
    TIMING_END("[normal data member]")
    TIMING_START
    b.seq_access(repeat_times, absorb_stdout);
    TIMING_END("[static data member]")
}

int main()
{
    ofstream absorb_stdout("tmp.txt");
    compare_static_data_member(absorb_stdout);
    return 0;
}

随机访问

上述seq_access改成:

void rand_access(int round, ostream &absorb_stdout)
{
    int total = 0;
    for (int i = 0; i < round; ++i)
        for (size_t j = 0, jed = nbrs.size(), pos, max_pos = jed - 1; j < jed; ++j)
        {
            pos = double(rand()) / RAND_MAX * max_pos;
            total += nbrs[pos];
        }
    absorb_stdout << total;
}

结果

顺序访问

重复30次顺序访问,nbrs元素个数100000000
不开O3:静态更快

[normal data member]10166058 us
[static data member]8635176 us

开O3:普通更快

[normal data member]831936 us
[static data member]893034 us

随机访问

100000000次随机访问nbrs
不开O3:普通更快

[normal data member]5354315 us
[static data member]5803599 us

开O3:静态略快

[normal data member]3785677 us
[static data member]3708722 us

评论