c++ lock 和 字符串赋值性能测试

先说结论:

1. 一个互斥锁消耗的时间大概可以跑100多次循环了。

2. string 赋值要比strcpy慢得多,不在同一个数量级。

#include 
#include 
#include 
#include 
#include < cstring> 
#include 

#include 

#ifndef Linux
#include 
#include 
#endif // !Linux

#include 

using namespace std;

class terra_spin_lock
{
public:
    terra_spin_lock()
    {}
    void lock()
    {
        _mutex.lock();
    }
    void unlock()
    {
        _mutex.unlock();
    }
private:
    std::mutex _mutex;
};

class terra_auto_lock
{
public:
    terra_auto_lock(terra_spin_lock* lock)
    {
        _lock = lock;
        _lock->lock();
    }

    ~terra_auto_lock()
    {
        _lock->unlock();
    }
private:
    terra_spin_lock* _lock;
};

int num = 10000000;
void f(int a)
{
    terra_spin_lock l;
    for (int i = 0; i <= num; ++i)
    {
        terra_auto_lock lock(&l);
    }
}

#define bb_size 102
int bb[bb_size] = { 0 };

void f2(int a)
{
    for (int i = 0; i <= num; ++i)
    {
        for (int j = 0; j < bb_size; ++j)
            if (bb[j] == 9)
                break;
    }
}

std::string str_bb[bb_size] = { "11"};
void f3(int a)
{
    for (int i = 0; i <= num; ++i)
    {
        for (int j = 0; j < bb_size; ++j)
        {
            str_bb[j] = "10";
        }
    }
}

char c_bb[bb_size] = { "" };
void f4(int a)
{
    for (int i = 0; i <= num; ++i)
    {
        for (int j = 0; j < bb_size; ++j)
        {
            strcpy(c_bb, "1145678966666666666666666666611456789666666666666666666666");
            //if (c_bb[j] == '9')
            //    break;
        }
    }
}

int main()
{
    cout << clock() << endl;
    auto t = std::thread(f, 1);
    t.join();
    cout << clock() << endl;
    auto t2 = std::thread(f2, 1);
    t2.join();
    cout << clock() << endl;

    auto t3 = std::thread(f3, 1);
    t3.join();
    cout << clock() << endl;

    auto t4 = std::thread(f4, 1);
    t4.join();
    cout << clock() << endl;

    return 0;
}
129
1529
3091
130342
140724

你可能感兴趣的:(c++,java,开发语言)