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> 源码分析

相关推荐
ADDDDDD_Trouvaille几秒前
2026.2.12——OJ72-74题
c++·算法
励ℳ9 分钟前
机器学习-LASSO算法指南
人工智能·算法·机器学习
郝学胜-神的一滴13 分钟前
TCP通讯的艺术:从握手到挥手的优雅对话
开发语言·网络·网络协议·tcp/ip·程序人生
黎雁·泠崖14 分钟前
【魔法森林冒险】12/14 场景系统:5大场景的任务串联
java·开发语言
l1t23 分钟前
在python 3.14 容器中安装和使用chdb包
开发语言·python·clickhouse·chdb
梵刹古音23 分钟前
【C++】函数重写
开发语言·c++
Titan202433 分钟前
C++异常学习笔记
c++·笔记·学习
Vic1010135 分钟前
算法D1-20260212:双指针专题
java·数据结构·算法
仟濹36 分钟前
【算法打卡day7(2026-02-12 周四)算法:BFS and BFS】10__卡码网110_字符串迁移, 11_卡码网105_有向图的完全连通
算法·深度优先·dfs·bfs·宽度优先