std::move性能测试和应用范例

string move正确用法与性能测试

直接上代码和运行结果

代码

#include <iostream>
#include <string>
#include <sys/time.h>
using namespace std;

const int kRunTime = 1000*1000;     // 循环次数
const int kStringLength = 100000;   // 字符串长度
void CreateStr(string& str)
{
    for(int i = 0; i < kStringLength; ++i)
        str += rand()%26 + 'a';
}

std::string GetStr(string& str)
{
    return std::move(str);
}

std::string GetStr2(string& str)
{
    return str;
}

int main()
{
    string str;
    string mov_str;
    CreateStr(str);     // 产生一个随机的字符串
    std::cout << "test string len = " << str.length() << ", loop times = " << kRunTime << std::endl;

    timeval st, et;
    gettimeofday(&st, NULL);
    for(int i = 0; i < kRunTime; ++i)
    {
        mov_str = std::move(GetStr(str));
        str = std::move(mov_str);
    }
    gettimeofday(&et, NULL);
    cout << "use std::move, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
    // 从这里打印mov_str.size = 0我们也可以看到被move的对象不能再被使用,因为其内存空间已经被转移到其他对象。
    cout << "mov_str.size = " << mov_str.size() << endl << endl;
    gettimeofday(&st, NULL);
    for(int i = 0; i < kRunTime; ++i)
    {
        mov_str = GetStr2(str);
        str = std::move(mov_str);
    }
    gettimeofday(&et, NULL);
    cout << "return directly in function, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
    cout << "mov_str.size = " << mov_str.size() << endl << endl;
    gettimeofday(&st, NULL);
    for(int i = 0; i < kRunTime; ++i)
    {
        mov_str = GetStr(str);
        str = (mov_str);
    }
    gettimeofday(&et, NULL);
    cout << "use assgin after function, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
    cout << "mov_str.size = " << mov_str.size() << endl;
    return 0;
}

运行结果

test string len = 100000, loop times = 1000000
use std::move, time:57ms
return directly in function, time:6513ms
use assgin after function, time:7561ms

正确用法

在函数内使用std::move返回,函数返回时仍用std::move赋值。
但是某对象在被使用std::move后,不能再正常地使用它。

参考

[1] string move正确用法与性能测试

全部评论

相关推荐

08-07 11:15
门头沟学院 Java
感觉他们公司效率好高,秒挂我简历然后又给我推荐了岗位让我投原批yyds
没有offer别哭好...:是的,然后我投了邮件里的链接,又秒挂了
投递米哈游等公司10个岗位
点赞 评论 收藏
分享
06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
我的简历长这样
点赞 评论 收藏
分享
天天困啊:个人建议第一点就是熟悉Redis这里不要这么写,写上Redis比较核心的技术,什么缓存一致性,雪崩穿透击穿那些,掌握cos其实不用写在专业技能里这个你做了鱼皮的这个项目面试官默认应该认为你应该懂了,鱼皮这个项目核心挺多建议多啃啃,在做一个鱼皮的微服务项目俩项目在一起比较好哦
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务