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

相关推荐
diygwcom1 分钟前
功能强大且易于使用的 JavaScript 音频库howler.js 和AI里如何同时文字跟音频构思想法
开发语言·javascript·音视频
etp_13 分钟前
C++:虚函数与纯虚函数
开发语言·c++
曦月逸霜21 分钟前
第十七次CCF-CSP算法(含C++源码)
开发语言·数据结构·c++·算法
single-tracking35 分钟前
关于vector、queue、list哪边是front、哪边是back,增加、删除元素操作
c++
yb0os137 分钟前
手写一个简单的线程池
java·开发语言·数据库·计算机·线程池·juc
Dxy123931021644 分钟前
Python Scikit-Learn核心流程
开发语言·python·scikit-learn
FL16238631291 小时前
[python]opencv从源码编译python版本发现不生成cv2.pyd
开发语言·python·opencv
患得患失9491 小时前
【算法】力扣体系分类
算法·leetcode·分类
Moutai码农1 小时前
机器学习算法-sklearn源起
算法·机器学习·sklearn
加什么瓦1 小时前
JVM——内存模型
java·开发语言·jvm