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

相关推荐
投笔丶从戎18 分钟前
Kotlin Multiplatform--01:项目结构基础
android·开发语言·kotlin
OpenC++28 分钟前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
杜小暑1 小时前
动态内存管理
c语言·开发语言·动态内存管理
想不明白的过度思考者1 小时前
Java从入门到“放弃”(精通)之旅——JavaSE终篇(异常)
java·开发语言
YuforiaCode1 小时前
第十二届蓝桥杯 2021 C/C++组 直线
c语言·c++·蓝桥杯
我真的不会C1 小时前
QT窗口相关控件及其属性
开发语言·qt
CodeCraft Studio1 小时前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
火柴盒zhang1 小时前
websheet之 编辑器
开发语言·前端·javascript·编辑器·spreadsheet·websheet
景天科技苑2 小时前
【Rust】Rust中的枚举与模式匹配,原理解析与应用实战
开发语言·后端·rust·match·enum·枚举与模式匹配·rust枚举与模式匹配
知来者逆2 小时前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr