vector<bool>性能测试

cpp 复制代码
#include <iostream>
#include <vector>
#include <sstream>
#include <numeric>
#include <string>
#include <unordered_map>
#include <queue>
#include <map>
using namespace std;


int main()
{
    clock_t t1, t2, t3;
    vector<bool> vb;
    vector<int> vi;
    vector<char> vc;

    t1 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            vb.push_back(true);
        }
    }
    t1 = clock() - t1;

    t2 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            vi.push_back(1);
        }
    }
    t2 = clock() - t2;

    t3 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            vc.push_back('a');
        }
    }
    t3 = clock() - t3;

    cout << "'vector<bool>::push_back(true)' 1000000 times cost: " << t1 << endl;
    cout << "'vector<int>::push_back(1)' 1000000 times cost: " << t2 << endl;
    cout << "'vector<char>::push_back('a')' 1000000 times cost: " << t3 << endl;

    t1 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            bool b = vb[j + 1000 * i];
        }
    }
    t1 = clock() - t1;

    t2 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            int b = vi[j + 1000 * i];
        }
    }
    t2 = clock() - t2;

    t3 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            char b = vc[j + 1000 * i];
        }
    }
    t3 = clock() - t3;

    cout << "'vector<bool>::operator[]' 1000000 times cost: " << t1 << endl;
    cout << "'vector<int>::operator[]' 1000000 times cost: " << t2 << endl;
    cout << "'vector<char>::operator[]' 1000000 times cost: " << t3 << endl;

    return 0;
}

测试结果

bash 复制代码
'vector<bool>::push_back(true)' 1000000 times cost: 4824
'vector<int>::push_back(1)' 1000000 times cost: 62
'vector<char>::push_back('a')' 1000000 times cost: 59
'vector<bool>::operator[]' 1000000 times cost: 312
'vector<int>::operator[]' 1000000 times cost: 5
'vector<char>::operator[]' 1000000 times cost: 6

原理:

vector<bool> 源码分析

相关推荐
信号处理学渣几秒前
matlab画图,选择性显示legend标签
开发语言·matlab
红龙创客几秒前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
Lenyiin3 分钟前
第146场双周赛:统计符合条件长度为3的子数组数目、统计异或值为给定值的路径数目、判断网格图能否被切割成块、唯一中间众数子序列 Ⅰ
c++·算法·leetcode·周赛·lenyiin
jasmine s10 分钟前
Pandas
开发语言·python
郭wes代码10 分钟前
Cmd命令大全(万字详细版)
python·算法·小程序
scan72425 分钟前
LILAC采样算法
人工智能·算法·机器学习
biomooc30 分钟前
R 语言 | 绘图的文字格式(绘制上标、下标、斜体、文字标注等)
开发语言·r语言
骇客野人33 分钟前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言
black^sugar35 分钟前
纯前端实现更新检测
开发语言·前端·javascript
404NooFound40 分钟前
Python轻量级NoSQL数据库TinyDB
开发语言·python·nosql