内存拷贝、锁执行时间测试

为了测试多生产者多消费者的瓶颈,写此测试,代码如下:

#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字节时,内存拷贝耗时比锁切换要大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值