c++性能之map实现性能比较

http://www.cnblogs.com/zhjh256/p/6346501.html讲述了基本的map操作,在测试的时候,发现-O0模式下,map的性能极为低下,与java相比相差了接近200倍。测试的逻辑如下:

    // map定义
    map<int, FirstCPPCls*> mapStudent;
    for (i=0;i<10000;i++) {
        FirstCPPCls clz;
        clz.setAppVersion("12.32.33");
        clz.setClusterName("osm-service");
        clz.setCompanyId("239383");
        clz.setServiceId("sysL.1.223");
        clz.setSubSystemId("23");
        clz.setSystemId("32");
        mapStudent.insert(pair<int, FirstCPPCls*>(i, &clz));
    }

    // 获取时间相对计数器, vc专用
    begin = GetTickCount();
    for (j=0;j<100;j++) {
        for (f=0;f<10000;f++) {
            // map查找
            mapStudent.find(f);
        }
    }
    end = GetTickCount();

    // 打印时间差
    cout << "Map查找耗时:" << (end - begin) << endl;  // 平均4秒左右
    system("pause");

在java中相同的实现,get 100 0000次只花费了20ms。于是搜索 c++ map性能,看了两个帖子如下:

http://blog.csdn.net/a418382926/article/details/22302907

http://blog.sina.com.cn/s/blog_5f93da790101hxxi.html

http://www.ideawu.net/blog/archives/751.html

随后,进行hash_map和unordered_map测试,如下:

    // hash_map定义
    hash_map<int, FirstCPPCls*> hash_mapStudent;
    for (i=0;i<10000;i++) {
        FirstCPPCls clz;
        clz.setAppVersion("12.32.33");
        clz.setClusterName("osm-service");
        clz.setCompanyId("239383");
        clz.setServiceId("sysL.1.223");
        clz.setSubSystemId("23");
        clz.setSystemId("32");
        hash_mapStudent.insert(pair<int, FirstCPPCls*>(i, &clz));
    }

    // 获取时间相对计数器, vc专用
    begin = GetTickCount();
    for (j=0;j<100;j++) {
        for (f=0;f<10000;f++) {
            // map查找
            hash_mapStudent.find(f);
        }
    }
    end = GetTickCount();

    // 打印时间差
    cout << "HashMap查找耗时:" << (end - begin) << endl;  // 平均4秒左右
    system("pause");

    // hash_map定义
    unordered_map<int, FirstCPPCls*> unordered_mapStudent;
    for (i=0;i<10000;i++) {
        FirstCPPCls clz;
        clz.setAppVersion("12.32.33");
        clz.setClusterName("osm-service");
        clz.setCompanyId("239383");
        clz.setServiceId("sysL.1.223");
        clz.setSubSystemId("23");
        clz.setSystemId("32");
        unordered_mapStudent.insert(pair<int, FirstCPPCls*>(i, &clz));
    }

    // 获取时间相对计数器, vc专用
    begin = GetTickCount();
    for (j=0;j<100;j++) {
        for (f=0;f<10000;f++) {
            // map查找
            unordered_mapStudent.find(f);
        }
    }
    end = GetTickCount();

    // 打印时间差
    cout << "UnorderedMap查找耗时:" << (end - begin) << endl;  // 平均4秒左右
    system("pause");

输出如下:

HashMap查找耗时:1610
请按任意键继续. . .
UnorderedMap查找耗时:1797
请按任意键继续. . .

虽然,相比std::map,确实提升了50%多,但是跟java,还是慢的一塌糊涂,因为对stl还没有研究,不确定具体什么原因导致。

采用-O2后,性能提升分别为30%~50%。

posted @ 2017-01-24 15:10  zhjh256  阅读(7199)  评论(3编辑  收藏  举报