为了测试多生产者多消费者的瓶颈,写此测试,代码如下:
#include <iostream>
#include <memory.h>
#include <sys/time.h>
#include <pthread.h>
#include <string.h>
using namespace std;
#define RUNTIME 10000000
int length = 100;
class SpinLock
{
public:
inline SpinLock();
inline bool Lock();
inline void Unlock();
inline virtual ~SpinLock();
private:
inline bool Init();
private:
pthread_spinlock_t lock_;
};
SpinLock::SpinLock()
{
Init();
}
bool SpinLock::Lock()
{
return 0 == pthread_spin_lock(&lock_);
}
void SpinLock::Unlock()
{
pthread_spin_unlock(&lock_);
}
SpinLock::~SpinLock()
{
pthread_spin_destroy(&lock_);
}
bool SpinLock::Init()
{
if (0 == pthread_spin_init(&lock_, 0))
{
return true;
}
else
{
return false;
}
}
SpinLock lock;
int assign_data;
void* RunLock(void *)
{
cout << "RunLock start!" << endl;
while(1)
{
lock.Lock();
assign_data = 5;
lock.Unlock();
}
return NULL;
}
int main()
{
struct timeval cpy_time_start, cpy_time_end, lock_time_start, lock_time_end, single_time_start, single_time_end;
//测试单独执行一条命令时间
gettimeofday(&single_time_start, NULL);
for(int i = 0; i < RUNTIME; ++i)
{
assign_data = 10;
}
gettimeofday(&single_time_end, NULL);
cout << "single cmd run " << RUNTIME << " times, cost:" <<
(single_time_end.tv_sec-single_time_start.tv_sec)*1000000+(single_time_end.tv_usec-single_time_start.tv_usec) << "us" << endl;
//测试内存拷贝时间随拷贝长度变化的变化
for(int i = 0; i < 4; ++i, length*=10)
{
char data[length];
char* ptr = (char *)malloc(length);
gettimeofday(&cpy_time_start, NULL);
for(int i = 0; i < RUNTIME; ++i)
{
memcpy(ptr, data, length);
}
gettimeofday(&cpy_time_end, NULL);
cout << "memcpy " << length << " data " << RUNTIME << " times, cost:" <<
(cpy_time_end.tv_sec-cpy_time_start.tv_sec)*1000000+(cpy_time_end.tv_usec-cpy_time_start.tv_usec) << "us" << endl;
}
pthread_t pid;
pthread_create(&pid, NULL, RunLock, NULL);
pthread_detach(pid);
//测试自旋锁耗时,可将其修改为互斥锁,当锁内执行操作简单时自旋锁速度快的多,本例中接近1/2
gettimeofday(&lock_time_start, NULL);
for(int i = 0; i < RUNTIME; ++i)
{
lock.Lock();
assign_data = 10;
lock.Unlock();
}
gettimeofday(&lock_time_end, NULL);
cout << "lock " << RUNTIME << " times, cost:" <<
(lock_time_end.tv_sec-lock_time_start.tv_sec)*1000000+(lock_time_end.tv_usec-lock_time_start.tv_usec) << "us" << endl;
pthread_join(pid, NULL);
return 0;
}
运行结果:
从中可以看出当拷贝长度超过10000字节时,内存拷贝耗时比锁切换要大。