← 历史存档

这是原站讨论区的存档(快照时间 2016-11-07),只读。

赛码会总结

shinian · 2016-09-01 00:12:49 · contest3

经过为期1个月,共20000次提交,赛马会第一期正式结束啦~
整场比赛非常精彩,先是由arthuryang领跑,最后driver和zjx20角逐rank1,在最后10分钟zjx20完成反杀夺得了第一。。。
首先恭喜top10的小伙伴。
他们是


我会私信联系top10的选手索要个人收货地址~奖品会在收到地址的2个工作日内发顺风快递。

另外我们会开放代码权限给各个关注此次赛事的公司主管,如果对方对您的代码感兴趣,会主动私信联系你的~!(比如driver同志已经被好多技术leader order了...)

接下去几楼分别是top5的最终版的代码,你可以审阅并继续提交测试,9.1号之后的提交不再影响排行榜。

19 个回答

shinian · 2016-09-01 00:15:07

rank1 zjx20

恭喜zjx20以400pqs的微弱优势获得hhkb pro键盘!
zjx20对c++非常熟...各种编译器级别的优化...

#include <string>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <functional>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

using namespace std;

// #define _DEBUG

#define IL __attribute__((always_inline))
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)

typedef size_t kk_t;
// TODO: tuning those numbers
const int SMALL_BUCKET_SIZE = 149969;
#define HASH(x) hash<string>()(x)
static string STR_NULL = "NULL";

// #pragma pack(1)

int open_file(const char* name, int size)
{
  int fd = open(name, O_RDWR|O_CREAT|O_NOATIME, S_IRUSR|S_IWUSR);
  struct stat sb; fstat(fd, &sb);
  if (sb.st_size == 0) {
    ftruncate(fd, size);
  }
  return fd;
}

bool file_exists(const char* name)
{
  struct stat buf;
  int result = stat(name, &buf);
  return result == 0;
}

struct IndexItem
{
  kk_t key;
  uint32_t pos;
  int32_t len;
};

class Answer {
  const int POS_BITS = 26; // 64MB
  const int POS_MASK = (1 << POS_BITS) - 1;
  const int SEG_BITS = 32 - POS_BITS;
  const int SEG_MASK = (1 << SEG_BITS) - 1;
  const int SEG_SIZE = 1 << POS_BITS;
  const int INMEM_SEGS = 1 << (28 - POS_BITS); // 2^28 = 256MB
  const int INMEM_SEGS_MASK = INMEM_SEGS - 1;

  // http://www.numberempire.com/primenumbers.php
  const int SMALL_BUCKETSIZE = 67003;
  const int MEDIUM_BUCKETSIZE = 620003; // lower bound: 400009
  const int LARGE_BUCKETSIZE = 67003;
public:
  Answer()
  {
    _level = 0;
    if (file_exists("is_small")) {
      _level = 1;
    } else if (file_exists("is_medium")) {
      _level = 2;
    } else if (file_exists("is_large")) {
      _level = 3;
    }

    _size = max(max(SMALL_BUCKET_SIZE, MEDIUM_BUCKETSIZE), LARGE_BUCKETSIZE);
    int map_size = sizeof(IndexItem) * (_size + 1);
    int fd = open_file("index", map_size);
    _begin = (IndexItem*)mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, 0);
    _end = _begin + _size;

    setvbuf ( stdout , NULL , _IOFBF , 16*1024*1024 );

    if (_level != 0) {
      setup_solution(_level, true);
    }
  }
  ~Answer()
  {}

  IL string get(const string& key) {
    // if (unlikely(_level == 0)) {
    //   return STR_NULL;
    // }

    kk_t k = HASH(key);
    IndexItem* item = _begin + (k) % _size;;
    while (true) {
      if (likely(!item->key || item->key == k)) {
        break;
      }
      if (unlikely(++item >= _end)) {
        item = _begin;
      }
    }
    if (likely(item->key)) {
      static string str;
      int len = item->len;
      str.resize(len);
      // _data.read(item->pos, item->len, (void*)str.c_str());
      uint32_t pos = item->pos;
      int seg = (pos >> POS_BITS) & SEG_MASK;
      int real_pos = pos & POS_MASK;
      if (likely(seg + INMEM_SEGS > _n)) {
        // return _map_base[seg & INMEM_SEGS_MASK] + real_pos;
        memcpy((void*)str.c_str(), _map_base[seg & INMEM_SEGS_MASK] + real_pos, len);
      } else {
        // static char buf[31*1024];
        pread(_fds[seg], (void*)str.c_str(), len, real_pos);
        // return buf;
      }
      return str;
    } else {
      return STR_NULL;
    }
  }

  IL void put(const string& key, const string& value) {
    if (unlikely(_level == 0)) {
      if (value.size() < 200) {
        _level = 1;
      } else if (value.size() < 5000) {
        _level = 2;
      } else {
        _level = 3;
      }
      setup_solution(_level, false);
    }

    int32_t len = value.size();

    kk_t k = HASH(key);
    IndexItem* item = _begin + (k) % _size;;
    while (true) {
      if (likely(!item->key || item->key == k)) {
        break;
      }
      if (unlikely(++item >= _end)) {
        item = _begin;
      }
    }

    if (item->key) {
      uint32_t pos = item->pos;
      int seg = (pos >> POS_BITS) & SEG_MASK;
      int real_pos = pos & POS_MASK;
      int aligned_len = (item->len + (sizeof(intptr_t) - 1)) & (~(sizeof(intptr_t) - 1));
      int v_len = value.size();
      if (seg + INMEM_SEGS > _n && aligned_len >= v_len) {
        memcpy(_map_base[seg & INMEM_SEGS_MASK] + real_pos, value.c_str(), v_len);
        item->len = v_len;
        return;
      }
    }

    // _data.write(value.c_str(), len)
    if (unlikely(_pos + len > SEG_SIZE)) {
      // msync(_map_base[_n&INMEM_SEGS_MASK], SEG_SIZE, MS_ASYNC);
      int n = ++_n;
      int slot = n & INMEM_SEGS_MASK;
      if (likely(_map_base[slot] != NULL)) {
        munmap(_map_base[slot], SEG_SIZE);
      }
      static char name[10] = "data.";
      name[5] = '0' + n / 10;
      name[6] = '0' + n % 10;
      _fds[n] = open_file(name, SEG_SIZE);
      char* base = (char*)mmap(NULL, SEG_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, _fds[n], 0);
      _map_base[slot] = base;
      _curr_write = base;
      _pos = 0;
      _nseg_mask = _n << POS_BITS;
    }
    uint32_t curr = _pos | _nseg_mask;
    memcpy(_curr_write, value.c_str(), len);
    int aligned_len = (len + (sizeof(intptr_t) - 1)) & (~(sizeof(intptr_t) - 1));
    _pos += aligned_len;
    _curr_write += aligned_len;

    item->key = k;
    item->pos = curr;
    item->len = len;
  }

private:
  uint32_t prefetch()
  {
    uint32_t eof = 0;
    for (IndexItem* it = _begin; it != _end; ++it) {
      if (it->key) {
        eof = max(eof, it->pos + it->len);
      }
    }
    return eof;
  }

  void setup_solution(int level, bool initialzing)
  {
    if (level == 1) {
      open("is_small", O_RDWR|O_CREAT|O_NOATIME, S_IRUSR|S_IWUSR);
      _size = SMALL_BUCKETSIZE;
      _end = _begin + _size;
    } else if (level == 2) {
      open("is_medium", O_RDWR|O_CREAT|O_NOATIME, S_IRUSR|S_IWUSR);
      _size = MEDIUM_BUCKETSIZE;
      _end = _begin + _size;
    } else {
      open("is_large", O_RDWR|O_CREAT|O_NOATIME, S_IRUSR|S_IWUSR);
      _size = LARGE_BUCKETSIZE;
      _end = _begin + _size;
    }

    uint32_t data_eof = 0;
    if (initialzing) {
      data_eof = prefetch();
    }

    // _data.init(data_eof);
    assert(sizeof(_map_base)/sizeof(_map_base[0]) >= INMEM_SEGS);

    _n = (data_eof >> POS_BITS) & SEG_MASK;
    _nseg_mask = _n << POS_BITS;
    _pos = data_eof ^ _nseg_mask;
    static char name[10] = "data.";
    for (int i=0; i<=_n; i++) {
      name[5] = '0' + i / 10;
      name[6] = '0' + i % 10;
      _fds[i] = open_file(name, SEG_SIZE);
    }
    memset(_map_base, 0, sizeof(_map_base));
    for (int i=max(_n-INMEM_SEGS+1, 0); i<=_n; i++) {
      char* base = (char*)mmap(NULL, SEG_SIZE,
          PROT_READ|PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fds[i], 0);
      _map_base[i&INMEM_SEGS_MASK] = base;
      _curr_write = base;
    }
    _curr_write += _pos;
  }

private:
  int _level;
  IndexItem* _begin;
  IndexItem* _end;
  int _size;
  
  uint32_t _pos;
  uint32_t _nseg_mask;
  char* _curr_write;
  char* _map_base[4];
  int _fds[32];
  int _n;
};

shinian · 2016-09-01 00:16:27

rank2 driver

非常优秀的代码,总共82行2210字节...短小精悍...以mmap为主配合hash表,各种细节处理非常赞,没有出现针对3个数据版本的配置表...

#include <cstring>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
using namespace std;
hash<string> ha;
const int BUCKET_SIZE=524287;
struct node {
    size_t key;
    unsigned int len=0,offset;
};
const static string SN="NULL";
class Answer {
    int dataFd,nodeFd;
    node* nodeBuf;
    unsigned int len;
    size_t t;
    char s[30010];
    unsigned int offset=0;
    int pagesize=1<<24;
    int pagenum=120;
    int nowpage;
    char* dataBuf[120];
    int pagelen=16;
public:
    Answer() {
        nodeFd=open("redis.index",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
        int sz=(BUCKET_SIZE+1)*sizeof(node);
        ftruncate(nodeFd,sz);
        nodeBuf = (node*)mmap(0,sz,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_POPULATE,nodeFd,0);
        dataFd=open("redis.data",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
        ftruncate(dataFd,pagesize*pagenum);
        for(int i=0;i<=BUCKET_SIZE;i++){
            if(offset>nodeBuf[i].offset+nodeBuf[i].len)continue;
            offset=nodeBuf[i].offset+nodeBuf[i].len;
        }
        nowpage=offset>>24;
        for(int i=0;i<=pagelen;i++){
            if(nowpage-i<0)break;
            dataBuf[nowpage-i] = (char*)mmap(0,pagesize,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_POPULATE,dataFd,(nowpage-i)<<24);
        }
    }
    string get(const string &key) {
        t=ha(key);
        int k=(t&BUCKET_SIZE+BUCKET_SIZE)&BUCKET_SIZE;
        while(nodeBuf[k].len) {
            if (nodeBuf[k].key==t) {
                int p=nodeBuf[k].offset>>24;
                if(p+pagelen>=nowpage)
                    return string(dataBuf[p]+(nodeBuf[k].offset&(pagesize-1)),nodeBuf[k].len);
                pread(dataFd,s,nodeBuf[k].len,nodeBuf[k].offset);
                return string(s,nodeBuf[k].len);
            }
            k=(k+7)&BUCKET_SIZE;
        }
        return SN;
    }
    void put(const string &key,const string &value) {
        t=ha(key);
        len=value.size();
        if(((offset+len-1)>>24)!=nowpage){
            if(nowpage>=pagelen)
            munmap(dataBuf[nowpage-pagelen],pagesize);
            nowpage++;
            dataBuf[nowpage]=(char*)mmap(0,pagesize,PROT_READ|PROT_WRITE,MAP_SHARED,dataFd,nowpage<<24);
            offset=nowpage<<24;
        }
        memcpy((char*)(dataBuf[nowpage] +(offset&(pagesize-1))),value.c_str(),len);
        int k=(t&BUCKET_SIZE+BUCKET_SIZE)&BUCKET_SIZE;
        while(nodeBuf[k].len&&nodeBuf[k].key!=t)k=(k+7)&BUCKET_SIZE;
          nodeBuf[k].key=t;
        nodeBuf[k].len=len;
        nodeBuf[k].offset=offset;
        offset+=len;
    }
};

shinian · 2016-09-01 00:17:42

rank3 sanjose

sanjose最早各种内嵌汇编的优化...

#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include<cstdio>
#include<cstdint>
#include<cstring>
#include<string>
using namespace std;
extern "C"{
#include<unistd.h>
#include<sys/mman.h>
#include<fcntl.h>
}
#define POOLSIZE 8192000
#define MAXSLOTS 500000
#define MC (260*1024*1024)
long long FILESIZE = 2317824000;

// // for small dataset
// #define POOLSIZE 368640
// #define MAXSLOTS 20800
// #define MC (16*1024*1024)
// long long FILESIZE = 25534464;

#define MCW (4*1024*1024)
#define IDXSIZE (1024*1024*4*4)
string strnul = "NULL";

#define POLY 0x82f63b78
static uint32_t crcTbl[8][256];
static void crc32c_init(void){
    uint32_t n, crc, k;
    for (n = 0; n < 256; n++) {
        crc = n;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crcTbl[0][n] = crc;
    }
    for (n = 0; n < 256; n++) {
        crc = crcTbl[0][n];
        for (k = 1; k < 8; k++) {
            crc = crcTbl[0][crc & 0xff] ^ (crc >> 8);
            crcTbl[k][n] = crc;
        }
    }
}
static inline uint32_t crc32(const char *buf){
    register uint64_t crc = 0xffffffff;
    crc ^= *(uint64_t *)buf;
    crc = crcTbl[7][crc & 0xff] ^
        crcTbl[6][(crc >> 8) & 0xff] ^
        crcTbl[5][(crc >> 16) & 0xff] ^
        crcTbl[4][(crc >> 24) & 0xff] ^
        crcTbl[3][(crc >> 32) & 0xff] ^
        crcTbl[2][(crc >> 40) & 0xff] ^
        crcTbl[1][(crc >> 48) & 0xff] ^
        crcTbl[0][crc >> 56];
    return (uint32_t)crc ^ 0xffffffff;
}
static inline uint32_t crc32t(const char *buf, size_t len){
    const char *next = buf;
    register uint64_t crc = 0xffffffff;
    while (len) {
        crc = crcTbl[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);
        len--;
    }
    return (uint32_t)crc ^ 0xffffffff;
}

struct rec
{
    uint32_t c32;
    uint16_t klen;
    uint16_t vlen;
    uint32_t pos;
    int next;
} __attribute__((packed));

class Answer{
public:
    Answer();
    ~Answer();
    string get(string key);
    void put(char *key, char *value);
private:
    int fd;
    FILE* pF;
    uint32_t cval;
    uint32_t hval;
    uint16_t klen;
    int *idx;
    char *buf;
    char *pbuf;
    char *cch;
    char *cchf;
    int nextSlot;
    char *pool;
    rec *ppool;
    rec *prec;
    rec trec;
    uint32_t nextPos;
    uint32_t lb_cch;
    uint32_t hb_cch;
    uint32_t fold(uint32_t c32){return (c32 & 0x003FFFFF) ^ ((c32 >> 16) & 0xFFC0);};
};
Answer::Answer(){
    crc32c_init();
    buf = new char[30*1024];
    char const *fname = "kv.idx";
    nextSlot = 1;               // 0 used as a flag
    nextPos = 0;
    if(access(fname, F_OK) != -1){
        fd = open(fname, O_RDWR);
    }else{
        fd = open(fname, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
        lseek(fd, FILESIZE-1, SEEK_SET);
        write(fd, "", 1);
    }
    pF = fdopen(fd, "rb+");
    pool = reinterpret_cast<char*>(mmap(NULL, POOLSIZE+IDXSIZE, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0));
    cchf = reinterpret_cast<char*>(mmap(NULL, MC+30*1024, PROT_READ, MAP_SHARED, fd, POOLSIZE+IDXSIZE));
    lb_cch = 0, hb_cch = MCW;
    cch = reinterpret_cast<char*>(mmap(NULL, MCW+30*1024, PROT_WRITE|PROT_READ, MAP_SHARED, fd, POOLSIZE+IDXSIZE+lb_cch));
    char c;
    for(int k=0; k*4096 < POOLSIZE+IDXSIZE; ++k)
        c = pool[k*4096];
    for(int k=0; k*4096 < MC+30*1024; ++k)
        c = cchf[k*4096];
    for(int k=0; k*4096 < MCW+30*1024; ++k)
        c = cch[k*4096];
    idx = reinterpret_cast<int*>(pool + POOLSIZE);
    ppool = reinterpret_cast<rec*>(pool);
    prec = ppool + 1;
    while(prec->klen != 0){
        if(prec->pos >= nextPos)
            nextPos = prec->pos + prec->vlen;
        ++nextSlot;
        ++prec;
    }
    madvise(pool, POOLSIZE+IDXSIZE, MADV_RANDOM);
    madvise(cchf, MC+30*1024, MADV_RANDOM);
    madvise(cch, MCW+30*1024, MADV_SEQUENTIAL);
}
Answer::~Answer(){
    delete [] buf;
    munmap(pool, POOLSIZE+IDXSIZE);
    munmap(cchf, MC+30*1024);
    munmap(cch, MCW+30*1024);
    close(fd);
}
string Answer::get(string key){
    klen = key.length();
    if(klen >= 8)
        cval = crc32(key.c_str());
    else
        cval = crc32t(key.c_str(), klen);
    hval = fold(cval);
    prec = ppool + idx[hval];
    while(prec != ppool){
        if(prec->c32 == cval && prec->klen == klen){
            if(prec->pos < MC){
                pbuf = cchf+prec->pos;
            }else if(prec->pos >= lb_cch && prec->pos < hb_cch){
                pbuf = cch+prec->pos-lb_cch;
            }else{
                fseek(pF, prec->pos+POOLSIZE+IDXSIZE, SEEK_SET);
                fread(buf, 1, prec->vlen, pF);
                pbuf = buf;
            }
            return string(pbuf, prec->vlen);
        }else{
            prec = ppool + prec->next;
        }
    }
    return strnul;
}
void Answer::put(char *key, char *value){
    trec.klen = strlen(key);
    if(trec.klen >= 8)
        trec.c32 = crc32(key);
    else
        trec.c32 = crc32t(key, trec.klen);
    hval = fold(trec.c32);
    trec.vlen = strlen(value);
    prec = ppool + idx[hval];
    while(prec != ppool){
        if(prec->c32 == trec.c32 && prec->klen == trec.klen){
            if(trec.vlen == prec->vlen && prec->pos < hb_cch && prec->pos >= lb_cch){
                pbuf = cch + prec->pos - lb_cch;
                if(memcmp(pbuf, value, trec.vlen) == 0){
                    return;
                }else{
                    memcpy(cch+prec->pos-lb_cch, value, trec.vlen);
                    // msync(cch+prec->pos-lb_cch, trec.vlen, MS_ASYNC);
                    return;
                }
            }else{
                if(nextPos >= hb_cch){
                    munmap(cch, MCW+30*1024);
                    lb_cch = (nextPos/MCW)*MCW, hb_cch = lb_cch + MCW;
                    cch = reinterpret_cast<char*>(mmap(NULL, MCW+30*1024, PROT_WRITE|PROT_READ, MAP_SHARED, fd, POOLSIZE+IDXSIZE+lb_cch));
                    madvise(cch, MCW+30*1024, MADV_SEQUENTIAL);
                }
                memcpy(cch+nextPos-lb_cch, value, trec.vlen);
                // msync(cch+nextPos-lb_cch, trec.vlen, MS_ASYNC);
                prec->vlen=trec.vlen;
                prec->pos = nextPos;
                nextPos += prec->vlen;
                // msync(prec, sizeof(rec), MS_ASYNC);
                return;
            }
        }else{
            prec = ppool + prec->next;
        }
    }
    prec = ppool + nextSlot;
    prec->next = idx[hval];
    prec->c32=trec.c32;
    prec->klen=trec.klen, prec->vlen=trec.vlen;
    prec->pos = nextPos;
    if(nextPos >= hb_cch){
        munmap(cch, MCW+30*1024);
        lb_cch = (nextPos/MCW)*MCW, hb_cch = lb_cch + MCW;
        cch = reinterpret_cast<char*>(mmap(NULL, MCW+30*1024, PROT_WRITE|PROT_READ, MAP_SHARED, fd, POOLSIZE+IDXSIZE+lb_cch));
        madvise(cch, MCW+30*1024, MADV_SEQUENTIAL);
    }
    memcpy(cch+nextPos-lb_cch, value, prec->vlen);
    // msync(cch+nextPos-lb_cch, prec->vlen, MS_ASYNC);
    nextPos += prec->vlen;
    idx[hval] = nextSlot;
    ++nextSlot;
    // msync(prec, sizeof(rec), MS_ASYNC);
    // msync(idx+hval, 4, MS_ASYNC);
}

shinian · 2016-09-01 00:18:14

rank4 arthuryang

arthuryang 没有用mmap,最基本的fopen+fwrite+fllush+fread..排到rank4

#include <stdio.h>
#include <math.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

hash<string> hash_fun;

const int MAX_SIZE   = 230000000;

const int MAX_NUM    = 200000;
const int MAX_HASH   = 200000;
const int MAX_INIT   = 300000000;

const int MAX_NUM_P  = 900000;
const int MAX_HASH_P = 800000;

struct node {
    size_t key;
    string value;
    node *next;

    node(){
        next = NULL;
    }
};

node hash_list[MAX_NUM];
node *hp;
node *h[MAX_HASH];
int now_num = 1;
node *now;
int k;
int all_size = 0;

inline void hash_put(const size_t &key, const string & value) {
    k = key % MAX_HASH;
    now = h[k];
    while(now) {
        if (now->key == key) {
            now->value = value;
            return;
        }
        now = now->next;
    }
    if (all_size >= MAX_SIZE) {
        return;
    }
    now = &hash_list[now_num];
    now->key = key;
    now->value = value;
    now->next = h[k];
    h[k] = now;
    now_num++;
    all_size += value.size() - 128;
}

inline string hash_get(const size_t &key) {
    now = h[key % MAX_HASH];
    while(now) {
        if (now->key == key) {
            return now->value;
            }
        now = now->next;
    }
    return "N";
}

struct point {
    size_t key;
    unsigned short int len;
    unsigned long int all_len;
    point *next;
    point() {
        next = NULL;
    }
};

point hash_point[MAX_NUM_P];
point *p[MAX_HASH_P];
point *hpp;
int now_p = 1;

inline void hash_put_point(const size_t &key, const int &len, const int &all_len) {
    k = key % MAX_HASH_P;
    hpp = p[k];
    while(hpp) {
        if (hpp->key == key) {
            hpp->len = len;
            hpp->all_len = all_len;
            return;
        }
        hpp = hpp->next;
    }
    hpp = &hash_point[now_p];
    hpp->key = key;
    hpp->len = len;
    hpp->all_len = all_len;
    hpp->next = p[k];
    p[k] = hpp;
    now_p++;
}

inline point *hash_get_point(const size_t &key) {
    hpp = p[key % MAX_HASH_P];
    while(hpp) {
        if (hpp->key == key) {
            return hpp;
        }
        hpp = hpp->next;
    }
    return NULL;
}


class Answer {
    FILE* fp;
    FILE* fpvalue;
    FILE* fin;
    FILE* fvalue;
    string infile;
    int num;
    size_t t;
    unsigned short int len;
    string st;
    char s[30010];
    unsigned long int all_len;
public:
    Answer() {
        num = 0;
        all_len = 0;
        fp = fopen("dict", "ab");
        char fp_buff[128 * 1024];
        char fvalue_buff[128 * 1024];
        setvbuf ( fp , fp_buff, _IOLBF , 122 * 1024 - 1 );
        fpvalue = fopen("dict_value", "ab");
        fin = fopen("dict", "rb");
        fvalue = fopen("dict_value", "rb");
               setvbuf ( fvalue , fvalue_buff, _IOLBF , 122 * 1024 - 1 );
        string value;
        value.reserve(30010);
        infile.reserve(30010);
        fseek(fp, 0, SEEK_END);
        int data_number = ftell(fp) / (sizeof(len) + sizeof(t));
        fseek(fp, 0, SEEK_SET);
        int insert_data = 1000000000;
        if (data_number <= 1024) {
            insert_data = 0;
        }
        while (fread(&len, sizeof(len), 1, fin)) {
            fread(&t, sizeof(t), 1, fin);
            hash_put_point(t, len, all_len);
            if (insert_data && num == 1024){
                insert_data = max(1024, int(data_number - MAX_INIT / (all_len / 1024.0) - 1000));
            }

            if (num == insert_data) {
                 fseek(fvalue, all_len, SEEK_SET);
            }

            if (num >= insert_data) {
                fread(s, sizeof(char), len, fvalue);
                s[len] = '\0';
                string ss(s);
                hash_put(t, ss);
            }
            num += 1;
            all_len += len;
        }
    }

    string get(const string &key) {
        t = hash_fun(key);

        st = hash_get(t);
        if (st != "N") {
            return st;
        }

        hpp = hash_get_point(t);
        if (hpp) {
            fseek(fvalue, hpp->all_len, SEEK_SET);
            fflush(fpvalue);
            fread(s, sizeof(char), hpp->len, fvalue);
            s[hpp->len] = '\0';
            return string(s);
        } else {
            return "NULL";
        }
    }

    void put(const string &key, const string &value) {
        t = hash_fun(key);
        len = value.size();
        fwrite(value.c_str(), len, 1, fpvalue);
        fwrite(&len, sizeof(len), 1, fp);
        fwrite(&t, sizeof(t), 1, fp);
        hash_put_point(t, len, all_len);
        all_len += len;
        hash_put(t, value);
    }

    ~Answer() {
        fclose(fp);
        fclose(fin);
    }
};

shehebe · 2016-09-01 00:32:28

厉害了,明天好好研究研究

v2excoc · 2016-09-01 01:48:25

top10都是神一般的存在,没有之一!!!

cheyulin · 2016-09-01 09:48:14

我的小数据版本代码,大家帮忙看看哪里改进?

MemoryTimeDisk ReadDisk WriteDataQPS/TPSInit Time
23932KB181ms6389KB1448KBsmall1457209/84985847ms
//
// Created by cheyulin on 8/26/16.
//
#ifndef KEYVALUESTORE_ANOTHER_IMPL_KEY_VALUE_H
#define KEYVALUESTORE_ANOTHER_IMPL_KEY_VALUE_H

#include <cstring>
#include <string>
#include <vector>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "fcntl.h"

#define DB_NAME "yche.db"
#define SMALL_SIZE 6000000

using namespace std;
constexpr int INT_SIZE = sizeof(int);
const static string NULL_STR = "NULL";

struct fast_hash_func {
    size_t operator()(const string &__s) const noexcept {
        return std::_Hash_impl::hash(__s.data(), 8);
    }
};

fast_hash_func hash_func;

struct key_value_info {
    string key_str_;
    string value_str;
};

class yche_map {
private:
    vector<key_value_info> hash_table_;
    size_t max_slot_size_{0};

public:
    void reserve(int size) {
        hash_table_.resize(size);
        max_slot_size_ = size;
    }

    string get(const string &key) {
        auto index = hash_func(key) % max_slot_size_;
        for (; hash_table_[index].key_str_.size() != 0; index = (index + 1) % max_slot_size_) {
            if (hash_table_[index].key_str_ == key) {
                return hash_table_[index].value_str;
            }
        }
        return NULL_STR;
    }

    void put(string &key, string &value) {
        auto index = hash_func(key) % max_slot_size_;
        for (; hash_table_[index].key_str_.size() != 0; index = (index + 1) % max_slot_size_) {
            if (hash_table_[index].key_str_ == key) {
                hash_table_[index].value_str = move(value);
                return;
            }
        }
        hash_table_[index].key_str_ = move(key);
        hash_table_[index].value_str = move(value);
    }
};

class Answer {
private:
    yche_map map_;
    char *mmap_buffer_;
    int fd_;
    int index_{0};
    int integer;
    string key_;
    string value_;
    int key_len_;
    int val_len_;

public:
    Answer() {
        map_.reserve(48000);
        fd_ = open(DB_NAME, O_RDWR | O_CREAT, 0600);
        struct stat st;
        fstat(fd_, &st);
        if (st.st_size != SMALL_SIZE)
            ftruncate(fd_, SMALL_SIZE);
        mmap_buffer_ = (char *) mmap(NULL, SMALL_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_POPULATE, fd_, 0);
        for (;;) {
            memcpy(&integer, mmap_buffer_ + index_, INT_SIZE);
            key_len_ = integer;
            if (key_len_ == 0)
                break;
            index_ += INT_SIZE;
            if (key_len_ != 0) {
                key_.assign(mmap_buffer_ + index_, key_len_);
                index_ += key_len_;
                memcpy(&integer, mmap_buffer_ + index_, INT_SIZE);
                val_len_ = integer;
                index_ += INT_SIZE;
                value_.assign(mmap_buffer_ + index_, val_len_);
                index_ += val_len_;
                map_.put(key_, value_);
            }
        }
    }

    string get(string key) {
        return map_.get(key);
    }

    void put(string key, string value) {
        key_len_ = key.size();
        memcpy(mmap_buffer_ + index_, &key_len_, INT_SIZE);
        index_ += INT_SIZE;
        memcpy(mmap_buffer_ + index_, key.c_str(), key_len_);
        index_ += key_len_;
        val_len_ = value.size();
        memcpy(mmap_buffer_ + index_, &val_len_, INT_SIZE);
        index_ += INT_SIZE;
        memcpy(mmap_buffer_ + index_, value.c_str(), val_len_);
        index_ += val_len_;
        map_.put(key, value);
    }
};

#endif //KEYVALUESTORE_ANOTHER_IMPL_KEY_VALUE_H

sanjose · 2016-09-01 10:22:34

跑Small数据集的代码,贴一下

#include<cstdio>
#include<cstdint>
#include<cstring>
#include<string>
using namespace std;
struct rec{
    uint32_t c32;
    uint16_t klen;
    uint16_t vlen;
    char buf[160];
} __attribute__((packed));
using array2d = rec*(*)[2];
extern "C"{
#include<unistd.h>
#include<sys/mman.h>
#include<fcntl.h>
}
string strnul = "NULL";
#define MAXSLOTS 20800

#define POLY 0x82f63b78
static uint32_t crcTbl[8][256];
static void crc32c_init(void){
    uint32_t n, crc, k;
    for (n = 0; n < 256; n++) {
        crc = n;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crcTbl[0][n] = crc;
    }
    for (n = 0; n < 256; n++) {
        crc = crcTbl[0][n];
        for (k = 1; k < 8; k++) {
            crc = crcTbl[0][crc & 0xff] ^ (crc >> 8);
            crcTbl[k][n] = crc;
        }
    }
}
static inline uint32_t crc32(const char *buf)
{
    uint64_t crc = 0xffffffff;
    crc ^= *(uint64_t *)buf;
    crc = crcTbl[7][crc & 0xff] ^
        crcTbl[6][(crc >> 8) & 0xff] ^
        crcTbl[5][(crc >> 16) & 0xff] ^
        crcTbl[4][(crc >> 24) & 0xff] ^
        crcTbl[3][(crc >> 32) & 0xff] ^
        crcTbl[2][(crc >> 40) & 0xff] ^
        crcTbl[1][(crc >> 48) & 0xff] ^
        crcTbl[0][crc >> 56];
    return (uint32_t)crc ^ 0xffffffff;
}
static inline uint32_t crc32t(const char *buf, size_t len)
{
    const char *next = buf;
    uint64_t crc = 0xffffffff;
    while (len) {
        crc = crcTbl[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);
        len--;
    }
    return (uint32_t)crc ^ 0xffffffff;
}

class Answer{
public:
    Answer();
    ~Answer();
    string get(string key);
    void put(char *key, char *value);
private:
    int fd;
    uint32_t cval;
    uint32_t hval;
    int klen;
    array2d idx;
    int nextSlot;
    rec *prec;
    rec trec;
    char *pool;
    rec *ppool;
    void restoreIndexFromFile();
    uint32_t fold(uint32_t c32){ return (c32 & 0x003FFFFF) ^ ((c32 >> 16) & 0xFFC0);};
};

Answer::Answer(){
    crc32c_init();
    idx = new rec*[4*1024*1024][2]();
    char const *fname = "kv.idx";
    nextSlot = 0;
    if(access(fname, F_OK) != -1){
        fd = open(fname, O_RDWR);
        pool = reinterpret_cast<char*>(mmap(NULL, MAXSLOTS*sizeof(rec), PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0));
        ppool = reinterpret_cast<rec*>(pool);
        restoreIndexFromFile();
    }else{
        fd = open(fname, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
        lseek(fd, MAXSLOTS*sizeof(rec)-1, SEEK_SET);
        write(fd, "", 1);
        pool = reinterpret_cast<char*>(mmap(NULL, MAXSLOTS*sizeof(rec), PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0));
        ppool = reinterpret_cast<rec*>(pool);
        char c;
        for(int k=0; k*4096 < MAXSLOTS*sizeof(rec); ++k)
            c = pool[k*4096];
    }
}
Answer::~Answer(){
    delete [] idx;
    munmap(pool, MAXSLOTS*sizeof(rec));
    close(fd);
}
string Answer::get(string key){
    klen = key.length();
    if(klen >= 8)
        cval = crc32(key.c_str());
    else
        cval = crc32t(key.c_str(), klen);
    hval = fold(cval);
    for(int i=0; i<2; ++i){
        if(idx[hval][i] == NULL){
            return strnul;
        }else{
            prec = idx[hval][i];
            if(prec->c32 == cval){
                return string(prec->buf, prec->vlen);
            }
        }
    }
    return strnul;
}
void Answer::put(char *key, char *value){
    trec.klen = strlen(key);
    trec.vlen = strlen(value);
    if(trec.klen >= 8)
        trec.c32 = crc32(key);
    else
        trec.c32 = crc32t(key, trec.klen);
    hval = fold(trec.c32);
    for(int i=0; i<2; ++i){
        if(idx[hval][i] == NULL){
            prec = ppool + nextSlot;
            prec->c32 = trec.c32;
            prec->klen = trec.klen;
            prec->vlen = trec.vlen;
            memcpy(prec->buf, value, prec->vlen);
            // msync(prec, sizeof(rec), MS_ASYNC);
            idx[hval][i] = prec;
            ++nextSlot;
            return;
        }else{
            prec = idx[hval][i];
            if(prec->c32 == trec.c32){
                if(prec->vlen == trec.vlen && strncmp(prec->buf, value, prec->vlen) == 0){
                    return;
                }else{
                    prec->vlen = trec.vlen;
                    memcpy(prec->buf, value, prec->vlen);
                    // msync(prec, sizeof(rec), MS_ASYNC);
                    return;
                }
            }else{
                continue;
            }
        }
    }
}
void Answer::restoreIndexFromFile(){
    prec = ppool+nextSlot;
    while(prec->klen != 0){
        hval = fold(prec->c32);
        for(int i=0; i<2; ++i){
            if(idx[hval][i] == NULL){
                idx[hval][i] = prec;
                break;
            }
        }
        ++nextSlot;
        prec += 1;
    }
}

shinian · 2016-09-01 10:55:48

arthuryang small

#include <stdio.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <unordered_map>
#include <vector>

#define MAX_NUM 100100
#define MAX_HASH (1<<16)

using namespace std;

hash<string> hash_fun;
//size_t hash_fun(const string & str)
//{
    //size_t hash = 5381;

    //for (char c : str) {
        //hash = ((hash << 5) + hash) + c; [> hash * 33 + c <]
    //}

    //return hash;
//}

struct node {
    size_t key;
    string value;
    int next;

    node(){
        value.reserve(200);
        next = 0;
    }
};

node hash_list[MAX_NUM];
node *hp;
int h[MAX_HASH];
int now_num = 1;
int now;
int k;

inline void hash_put(const size_t &key, const string & value) {
    k = key & 0xffff;
    now = h[k];
    while(now) {
        if (hash_list[now].key == key) {
             hash_list[now].value = value;
             return;
        }
        now = hash_list[now].next;
    }
    hash_list[now_num].key = key;
    hash_list[now_num].value = value;
    hash_list[now_num].next = h[k];
    h[k] = now_num++;
}

inline string hash_get(const size_t &key) {
    now = h[key & 0xffff];
    while(now) {
        hp = &hash_list[now];
        if (hp->key == key) {
             return hp->value;
            }
        now = hp->next;
    }
    return "NULL";
}


class Answer {
    FILE* fp;
    unordered_map<size_t, string> m;
    vector<string> v;
    unordered_map<size_t, string>::iterator p;
    string infile;
    int num;
    size_t t;
    unsigned char len;
public:
    Answer() {
        num = 0;
        fp = fopen("dict", "a");
        FILE *fin = fopen("dict", "rb");
        string value;
        value.reserve(300);
        infile.reserve(300);
        char s[300];
        while (fread(&len, sizeof(len), 1, fin)) {
            //cout << int(len) << endl;
            fread(&t, sizeof(t), 1, fin);
            fread(s, sizeof(char), len, fin);
            s[len] = '\0';
            string str(s);
            //m[t] = str;
            hash_put(t, str);
        }
        fclose(fin);
    }

    string get(const string &key) {
        return hash_get(hash_fun(key));
        //p = m.find(hash_fun(key));
        //if (p != m.end()) {
            //return p->second;
        //} else {
            //return "NULL";
        //}
    }

    void put(const string &key, const string &value) { //存储KV
        t = hash_fun(key);
        len = value.size();
        hash_put(t, value);
        fwrite(&len, sizeof (len), 1, fp);
        fwrite(&t, sizeof (size_t), 1, fp);
        fwrite(value.c_str(), 1, len, fp);

        //m[t] = value;
    }

    ~Answer() {
        fclose(fp);
    }
};

shinian · 2016-09-01 10:58:57

blahgeek rank5

#define _GNU_SOURCE
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <assert.h>
#include <sys/uio.h>
#include <vector>
#include <string>
#include <utility>

using std::string;

// #define MAX_MEM_SIZE (256 * 1024 * 1024)
#define MAX_VALUE_LENGTH (32 * 1024)

#define HASH_ENTRY (1 * 1024 * 1024)
#define HASH_PREFIX_LEN (8)

#define METAFILE_EXPAND_SIZE (32 * 1024 * 1024)
#define VALUEFILE_INITIAL_SIZE (512 * 1024 * 1024)

#define MAX_INLINE_VALUE_SIZE (28 * 1024)
#define MAX_INLINE_MEM_SIZE (288 * 1024 * 1024)

#define    FORCE_INLINE inline __attribute__((always_inline))

asm(
".text\n"
".p2align 4,,15\n"
".globl    MurmurHash2\n"
".type    MurmurHash2, @function\n"
"MurmurHash2:\n"
".cfi_startproc\n"
"cmpl    $3, %esi\n"
"movl    %esi, %eax\n"
"jle    .L2_mmh\n"
"leal    -4(%rsi), %r9d\n"
"movl    %r9d, %r8d\n"
"shrl    $2, %r8d\n"
"movl    %r8d, %eax\n"
"leaq    4(%rdi,%rax,4), %rcx\n"
".p2align 4,,10\n"
".p2align 3\n"
".L3_mmh:\n"
"imull    $1540483477, (%rdi), %eax\n"
"addq    $4, %rdi\n"
"movl    %eax, %edx\n"
"shrl    $24, %edx\n"
"xorl    %edx, %eax\n"
"imull    $1540483477, %esi, %edx\n"
"imull    $1540483477, %eax, %esi\n"
"xorl    %edx, %esi\n"
"cmpq    %rcx, %rdi\n"
"jne    .L3_mmh\n"
"negl    %r8d\n"
"leal    (%r9,%r8,4), %eax\n"
".L2_mmh:\n"
"cmpl    $2, %eax\n"
"je    .L5_mmh\n"
"cmpl    $3, %eax\n"
"je    .L6_mmh\n"
"cmpl    $1, %eax\n"
"je    .L7_mmh\n"
".L4_mmh:\n"
"movl    %esi, %eax\n"
"shrl    $13, %eax\n"
"xorl    %eax, %esi\n"
"imull    $1540483477, %esi, %eax\n"
"movl    %eax, %esi\n"
"shrl    $15, %esi\n"
"xorl    %esi, %eax\n"
"ret\n"
".p2align 4,,10\n"
".p2align 3\n"
".L6_mmh:\n"
"movzbl    2(%rdi), %eax\n"
"sall    $16, %eax\n"
"xorl    %eax, %esi\n"
".L5_mmh:\n"
"movzbl    1(%rdi), %eax\n"
"sall    $8, %eax\n"
"xorl    %eax, %esi\n"
".L7_mmh:\n"
"movzbl    (%rdi), %eax\n"
"xorl    %eax, %esi\n"
"imull    $1540483477, %esi, %esi\n"
"jmp    .L4_mmh\n"
".cfi_endproc\n"
);

extern "C" uint32_t MurmurHash2 ( const void *, int);

// for settings length of std::string without initialization
struct _string_layout {
    void * _;
    string::size_type length;
};
#define STR_SET_LEN(s, l) do{reinterpret_cast<struct _string_layout *>(&(s))->length = (l);}while(0)


static const std::string NULLSTR = std::string("NULL");

class Answer {

private:
    typedef struct {
        uint32_t meta_data_size;
        uint32_t value_data_size;
        uint32_t data_offsets[HASH_ENTRY];
    } Header;
    typedef struct {
        uint32_t key_hash;
        uint32_t key_length;
        uint32_t value_offset; // 0: inline
        uint32_t value_length;
        uint32_t next_offset;
        char value[];
    } Key;

    int meta_fd, value_fd;
    int meta_filesize, value_filesize;

    void * _data; // mmap of meta file
    Header * header; // same as _data

    string value_tmp;

public:
    Answer() {
        meta_fd = open("meta.dat", O_RDWR | O_CREAT, S_IRWXU);
        meta_filesize = lseek(meta_fd, 0, SEEK_END);
        bool initial = false;
        if (meta_filesize < METAFILE_EXPAND_SIZE) {
            meta_filesize = METAFILE_EXPAND_SIZE;
            ftruncate(meta_fd, meta_filesize);
            initial = true;
        }

        _data = mmap(NULL, meta_filesize, PROT_READ | PROT_WRITE, MAP_SHARED, meta_fd, 0);
        header = (Header *)_data;
        if (initial) {
            header->meta_data_size = sizeof(Header);
            header->value_data_size = 0;
            memset(header->data_offsets, 0, sizeof(uint32_t) * HASH_ENTRY);
        }

        value_fd = open("value.dat", O_RDWR | O_CREAT, S_IRWXU);
        value_filesize = lseek(value_fd, 0, SEEK_END);
        posix_fadvise(value_fd, 0, value_filesize, POSIX_FADV_RANDOM);

        value_tmp.reserve(MAX_VALUE_LENGTH);

        mlock(_data, meta_filesize);
        this->dedup();
    }

    void dedup_single(Key * k) {
        uint32_t * np_offset = &(k->next_offset);
        while (*np_offset != 0) {
            Key * nk = (Key *)((char *)_data + *np_offset);
            if (k->key_length == nk->key_length && k->key_hash == nk->key_hash)
                *np_offset = nk->next_offset;
            else
                np_offset = &(nk->next_offset);
        }
    }

    void dedup_full(int n) {
        uint32_t * p_start = header->data_offsets + n;
        while(*p_start != 0) {
            Key * k = (Key *)((char *)_data + *p_start);
            this->dedup_single(k);
            p_start = &(k->next_offset);
        }
    }

    void dedup() {
        for(int n= 0 ; n< HASH_ENTRY ; n+= 1)
            this->dedup_full(n);
    }

    string get(const string & key) {
        const char * key_p = key.c_str();
        int key_len = key.length();

        uint32_t key_hash = MurmurHash2(key_p, key_len > HASH_PREFIX_LEN ? HASH_PREFIX_LEN : key_len);
        uint32_t hash_idx = key_hash % HASH_ENTRY;
        uint32_t offset = header->data_offsets[hash_idx];

        while (offset != 0) {
            Key * k = (Key *)((char *)_data + offset);
            if (key_hash == k->key_hash && key_len == k->key_length) {
                int value_len = k->value_length;
                char * value_p = (char *)value_tmp.c_str();

                if (k->value_offset != 0)
                    pread(value_fd, value_p, value_len, k->value_offset);
                else // inline value
                    return std::string(k->value, value_len);
                    // memcpy(value_p, k->value, value_len);
                value_p[value_len] = '\0';
                STR_SET_LEN(value_tmp, value_len);

                return value_tmp;
            }

            offset = k->next_offset;
        }
        return NULLSTR;
    }

    void put(const string & key, const string & value) {
        uint32_t value_offset = 0;
        const char * value_p = value.c_str();
        int value_len = value.length();
        const char * key_p = key.c_str();
        int key_len = key.length();

        if (meta_filesize >= MAX_INLINE_MEM_SIZE || value_len >= MAX_INLINE_VALUE_SIZE) {
            // append to value_fd
            if (header->value_data_size + value_len >= value_filesize) {
                value_filesize = (value_filesize < VALUEFILE_INITIAL_SIZE) ? VALUEFILE_INITIAL_SIZE : (2 * value_filesize);
                ftruncate(value_fd, value_filesize);
                posix_fadvise(value_fd, 0, value_filesize, POSIX_FADV_RANDOM);
            }

            pwrite(value_fd, value_p, value_len, header->value_data_size);
            value_offset = header->value_data_size;
            header->value_data_size += value_len;
        }

        if (header->meta_data_size + sizeof(Key) + value_len >= meta_filesize) {
            meta_filesize += METAFILE_EXPAND_SIZE;
            ftruncate(meta_fd, meta_filesize);
            _data = mremap(_data, meta_filesize - METAFILE_EXPAND_SIZE, meta_filesize, MREMAP_MAYMOVE);
            mlock(_data, meta_filesize);
            header = (Header *)_data;
        }

        uint32_t key_hash = MurmurHash2(key_p, key_len > HASH_PREFIX_LEN ? HASH_PREFIX_LEN : key_len);
        uint32_t hash_idx = key_hash % HASH_ENTRY;
        Key * k = (Key *)((char *)_data + header->meta_data_size);
        k->key_hash = key_hash;
        k->key_length = key_len;
        k->value_offset = value_offset;
        k->value_length = value_len;
        k->next_offset = header->data_offsets[hash_idx];
        if (value_offset == 0)
            memcpy(k->value, value_p, value_len);

        int offset = header->meta_data_size;
        header->meta_data_size += sizeof(Key) + ((value_offset == 0) ? value_len : 0);
        header->data_offsets[hash_idx] = offset;

        // this->dedup_single(hash_idx);
        // this->dedup_single(k);
    }
};

shinian · 2016-09-01 11:14:10

奥利奥的java版本

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

public class SCache {
    private byte[] buf = new byte[10000];
    private int bufLen = 0;
    private ByteBuffer indexBuffer;
    private ByteBuffer dataBuffer;
    private ArrayList<RandomAccessFile> dataFiles = new ArrayList<>();
    private FileChannel dataChannel;
    private int dataFileCount = 0;
    private int indexSize = 10 * 1000 * 1000;
    private int dataSize = 50 * 1000 * 1000;
    private int dataPosition = 1;

    public SCache() throws IOException {
        dataFileCount = 0;
        if (Files.exists(Paths.get("index"))) {
            indexBuffer = new RandomAccessFile("index", "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, indexSize * 4 + 20);
            indexBuffer.position(indexSize * 4 + 4);
            dataFileCount = indexBuffer.getInt();
            for (int i = 0; i < dataFileCount - 1; i++) {
                RandomAccessFile file = new RandomAccessFile("data" + i, "r");
                dataFiles.add(file);
            }
            dataPosition = indexBuffer.getInt();
            Path path = Paths.get("data" + (dataFileCount - 1));
            dataChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
            dataBuffer = dataChannel.map(FileChannel.MapMode.READ_WRITE, 0, dataSize);
            dataBuffer.position(dataPosition % dataSize);
        } else {
            indexBuffer = new RandomAccessFile("index", "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, indexSize * 4 + 20);
            dataFileCount = 0;
            dataBuffer = getDataBuffer();
        }
    }

    private ByteBuffer getDataBuffer() throws IOException {
        if (dataBuffer != null) {
            dataChannel.close();
            RandomAccessFile file = new RandomAccessFile("data" + (dataFileCount - 1), "r");
            dataFiles.add(file);
        }

        Path path = Paths.get("data" + dataFileCount);
        path.toFile().createNewFile();
        dataChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
        MappedByteBuffer buffer = dataChannel.map(FileChannel.MapMode.READ_WRITE, 0, dataSize);
        buffer.put((byte) 'S');
        dataPosition = dataFileCount * dataSize + 1;
        dataFileCount++;
        indexBuffer.position(indexSize * 4 + 4);
        indexBuffer.putInt(dataFileCount);
        return buffer;
    }

    private int getDataInt(int pos) throws IOException {
        if (pos >= dataPosition - dataPosition % dataSize) {
            int position = dataBuffer.position();
            int ret = dataBuffer.getInt(pos % dataSize);
            dataBuffer.position(position);
            return ret;
        } else {
            int fileIndex = pos / dataSize;
            RandomAccessFile file = dataFiles.get(fileIndex);
            file.seek(pos % dataSize);
            return file.readInt();
        }
    }

    private void getData(int pos, int length) throws IOException {
        if (pos >= dataPosition - dataPosition % dataSize) {
            int position = dataBuffer.position();
            dataBuffer.position(pos % dataSize);
            dataBuffer.get(buf, 0, length);
            bufLen = length;
            dataBuffer.position(position);
        } else {
            int fileIndex = pos / dataSize;
            RandomAccessFile file = dataFiles.get(fileIndex);
            file.seek(pos % dataSize);
            file.read(buf, 0, length);
            bufLen = length;
        }
    }

    public void put(String key, String value) throws IOException {
        int hash = Math.abs(key.hashCode()) % indexSize * 4;
        int dataInc = 8 + key.length() + value.length();
        if (dataPosition % dataSize + dataInc >= dataSize) {
            dataBuffer = getDataBuffer();
        }
        dataBuffer.putInt(key.length());
        dataBuffer.putInt(value.length());
        dataBuffer.put(key.getBytes());
        dataBuffer.put(value.getBytes());
        while (true) {
            indexBuffer.position(hash);
            int index = indexBuffer.getInt();
            if (index == 0) {
                indexBuffer.position(hash);
                indexBuffer.putInt(dataPosition);
                break;
            } else {
                int keyLen = getDataInt(index);
                getData(index + 8, keyLen);
                if (compareString(key)) {
                    indexBuffer.position(hash);
                    indexBuffer.putInt(dataPosition);
                    break;
                } else {
                    hash = (hash + 4) % (indexSize * 4);
                }
            }
        }
        dataPosition += dataInc;
        indexBuffer.position(indexSize * 4 + 8);
        indexBuffer.putInt(dataPosition);
    }

    public String get(String key) throws IOException {
        int hash = Math.abs(key.hashCode()) % indexSize * 4;
        while (true) {
            indexBuffer.position(hash);
            int position = indexBuffer.getInt();
            if (position == 0) {
                return "NULL";
            }
            int keyLen = getDataInt(position);
            getData(position + 8, keyLen);
            if (compareString(key)) {
                int valLen = getDataInt(position + 4);
                getData(position + 8 + keyLen, valLen);
                return new String(buf, 0, bufLen, Charset.forName("UTF-8"));
            } else {
                hash = (hash + 4) % (indexSize * 4);
            }
        }
    }

    boolean compareString(String s) {
        if (s.length() != bufLen) {
            return false;
        } else {
            byte[] b = s.getBytes();
            for (int i = 0; i < bufLen; i++) {
                if (b[i] != buf[i]) {
                    return false;
                }
            }
            return true;
        }
    }

    public static void main(String[] args) throws Exception {

        long t1 = System.currentTimeMillis();
        Random r = new Random();

        SCache cache = new SCache();
        Map<String, String> mp = new HashMap<>();
        for (int i = 0; i < 1000000; i++) {
            long a = r.nextLong();
            long b = r.nextLong();
            String k = Long.toBinaryString(a);
            String v = Long.toBinaryString(b);
            mp.put(k, v);
            cache.put(k, v);
        }
        long t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
        Set<String> st = mp.keySet();
        int cnt = 0;
        for (String s : st) {
            String v1 = mp.get(s);
            String v2 = cache.get(s);
            cnt++;
            if (!v1.equals(v2)) {
                System.out.println(cnt + ":" + v1 + "===" + v2);
                throw new Exception("wrong answer");
            }
        }
        long t3 = System.currentTimeMillis();
        System.out.println(t3 - t2);

    }
}

凯文桑 · 2016-09-01 15:43:48

那啥。。。啥时候开第二期?

v2excoc · 2016-09-01 16:12:29

拜一下大神先,顺便做一下笔记。。

  1. 打开文件用O_NOATIME,对写入有速度加成。

  2. 在small的情况下,用SuperFastHash之类的自定义算法,只对key的前8个BYTE数据做hash,要比std::hash<string>系统自带完整hash来的快一点。(small数据量很小,也并不会造成hash冲撞。)

  3. 在small的情况下,把get函数里,return string(buf, len);这句改成固定内存预分配模式,用string.reserve()函数预先分配,用STR_SET_LEN设置长度,免去底层内存分配的调用,对查询速度有加成。(参见rank5代码)

sanjose · 2016-09-01 16:18:17

zjx20、driver、arthuryang等几位大神的代码确实漂亮,让人眼前一亮。我先写写我的思路,给大家抛砖引玉。

我是在V2上看到@mickeyandkaka的帖子过来的,说这边高手如云,我就过来跟高手学习学习。

我理解这期赛码会要求写的是一个基于内存、磁盘两级存储的哈希表,有内存和磁盘用量的限制,我就从这三方面记一下我的思路。

哈希表构造

一个哈希表数据结构主要有三块儿内容,哈希函数、哈希表(这里指存储槽位的表)和记录。

哈希函数有很多可选,FNV-1、CityHash等,我用了CRC和MurmurHash,对,CRC除了做校验,用作哈希效果也不错。试下来CRC和MurmurHash的冲突率都很低,性能上两者也是在伯仲之间。

哈希表中槽位数的多少直接影响装载因子,我倾向于浪费点内存降低装载因子。代码中创建了2^22个槽位,每个槽位放一个int,算下来大小总共16M,还是可以接受的。将哈希值映射到槽位也有多种方法,用mod取模或者乘法散列法等。我的哈希表刚好对应22位的地址空间,于是采取了将32位哈希值直接折叠到22位的方法,在fold函数中实现。解决冲突用的是简单的链地址法,因为装载因子比较低,用开放寻址法我认为也不会有什么问题。

记录中主要存的是value的值,还要存key的长度、value的长度等,对应struct rec。value的值可以很长而且是变长的,因此可以有几种不同的处理方式:

  1. 按value的最大长度将value放在结构体内

  2. 将value单独拿出来,按实际长度顺序存储

  3. 将value单独拿出来,按最大长度顺序存储

方式1适合value比较短的场景,方式2、3适合value较长的场景;方式1、3在遇到对已存在key的大量update的时候能够方便地复写原value的存储区,而方式2只能分配新存储区;方式2需要在结构体中记录value的偏移量,方式3中如果value存储区的分配跟结构体的分配同步则可以直接算出地址;方式2、3容易将大量put实现为顺序写,方式1随机写的比率会比较高。综合来看,因small数据集的数据量比较小,能全部放在内存中,用方式1或3是比较合适的。我现在贴的代码中Middle和Large数据集用的是方式2,为Middle写过一个用方式3的实现,一直报RuntimeError,后来没有去管了。

存储结构

前面三部分内容,哈希函数在可执行文件中,记录肯定是要我们存储到磁盘的,哈希表则可存可不存,如果不存需要在构造函数中重建。

贴出的对应small数据集的代码是没有存储哈希表的,在restoreIndexFromFile函数中重建,而对应Middle和Large数据集的代码是存储了哈希表的,大小为IDXSIZE的部分。

我将哈希表和记录存储到了一个文件里,分开写到两个或三个文件中当然也没问题。文件分为三个区域,前两个区域的大小依次为POOLSIZE和IDXSIZE,分别存储struct rec和哈希表,第三个区域存储value的值。

每次重启程序后映射地址会变,因此哈希表和struct rec的next字段中存储的都是相对地址。如果在mmap调用中指定要映射到的虚存地址,那么这里写绝对地址也是可以的,不过到现在我还没试过。

内存结构

内存结构比较简单,哈希表和struct rec都通过mmap映射到内存,分别对应idx和ppool。映射一段MCW大小的区域cch,用于向文件尾追加写value值,写完一段就重新映射到下一段,映射段随着写入向前移动。

对于已存在key的update,我前期的代码中会往前找到原value的存储区,如果存储区够大就复写在该区域,否则写到文件尾,现在贴的代码中只会去检查是不是新旧value相同,其他情况一律写到文件尾,留下这个判断是考虑避免大量重复键值对的put请求让文件快速膨胀,但是测试数据中貌似没有这样的场景,去掉这个分支判断可以略微提高点写入速度。

对于剩下的内存,全部用作对存储value值的文件区域的缓存,代码中是cchf,大小为MC。这样做缓存非常简单,对于update请求不多的场景效果还是不错的,但是update请求很多的话,新的value被追加到文件尾,前面的value大量失效,这时缓存的效率就不高了(多个mmap块滚动映射能解决这个问题,具体写法参考driver大神的代码)。另外,这样缓存的是存在文件中的一串char,命中的时候仍然需要构造一次string返回。另一种构造缓存的方法是在缓存中存放string对象。对象的构造过程可以只放在构造函数和put中进行,这样可以有效提高get的速度,而put的速度有所下降,我按这个策略写的代码在跑Large数据集的时候效果不错。也可以不在put中构造缓存,而是在get中构造,先查缓存,如果缓存中没有就从文件读取char,构造string并存入缓存,然后返回string,这个策略试下来,get速度降低很显著,意味着测试数据中get的key重复率比较低。

才疏学浅,写的有疏漏还请各位高手指正。

driver · 2016-09-01 17:40:05

赛程思路

不爽,炒鸡不爽!!!8月25号我遥遥领先。。。每天上班闲暇之余,脑中便开始幻想hhkb丝滑的触感。。。

然而最后3天简直是噩梦

zjx20是不是qlcoder的工作人员,无论我怎么优化!!!他总能在半小时内冒出来,再以比我高一点点的qps反超我。。。我寝食难安,一直在抠小细节优化,终于在8月31号优化了一个版本以12k QPS的巨大的优势力压了zjx20,在8.31号23点40分再看了一眼排行榜,仍然以10k的优势力压zjx20,安安心心睡大觉。。。

第二天早上到公司,泡了杯82年的速溶咖啡,坐下,2颗方糖,拿起勺子摇匀,去除上面少许的漂浮的泡沫,吹一口气,打开mac,我第一的排行榜页面仍然映入眼帘清晰可见,静静的坐着,享受着胜利的愉悦,哎,无敌是多么寂寞。顺手按了下command+r刷新页面:

。。。。

。。。。

。。。。

。。。。

揉揉眼睛

。。。。

。。。。

。。。。

。。。。

。。。。

。。。。

F*,我怒锤了一下桌子,咖啡贱了我一脸。

九月的第一天就是在这种心情下度过的:

吐槽完了分享下思路

我看到题的第一天,写了一个比较基础的版本,一开始想着先怎么优化put。

fopen一个文件,fwrite写key和value,然后fflush or fsync 落盘。

很明显每次fflush是很慢的,尝试不调用fflush马上就wrong answer了,数据出得还是比较好的。

put的瓶颈我个人觉得就是在如何优化fflush了。

题目里说明了模拟断电的方式是通过kill -9,这让我很天然的想到了mmap,由于我的工作主要和redis以及hbase相关,之前工作中经常接触mmap,知道在程序异常退出的时候,哪怕mmap的内存数据并没有落盘,kernel也会在你的进程被kill之后,回写到磁盘。这里就已经是内核态的操作了,只要服务器不真正的断电,数据的安全性是有保证的。

于是我很快就用mmap的版本替换掉了fwrite的版本,TPS在small的数据集里马上能到120w++。

再后来发现key只要你hash函数设计好,其实是不用存的,直接通过c++内置的hash把key从string类型变成了size_t。那put函数只需要一个顺序写value的文件,外加一个或者多个索引相关的index文件就行了。

index用以确定value在具体文件中的position和len。

data文件存所有的value。

这个时候就考虑怎么构造索引结构来加速get了。

一般索引主要的方式就是 平衡树 或者 hash。

平衡树索引的优势在于空间占用相对小,时间复杂度是Log n。

hash只要你开得足够大,查询就是O(1)的。

这次最终的评价标准是时间(QPS+TPS),空间只要不超就行了。因此没理由选择平衡树,我写了一个比较裸的hash就已经有非常不错的QPS了。

这个时候我的初试版本就差不多定型了。但是发现init time和memory都没有真正的用完。就想有没有可能利用init time和memory本身构造一个缓存,加速get查询。最后我用类似滚动数组的方式缓存了16段mmap的区域,每块区域16M,总共256M,外加hash表大约占用了40M,刚好用完了300M内存。这个时候已经是排第一了。

我后来想字符集既然是base64的,我应该可以用base64 encode和base64 decode去优化25%的磁盘存储,这样内存中能有更多的空间作为缓存区域,查询效率也就相对高了。然后发现这个encode和decode本身消耗了太多太多的时间。如果这是一个8核的服务器,另外7个核来做encode和decode,那这点是成立的。

另外一个小优化,在做mmap内存映射的时候,其实kernel并没有把磁盘里的数据load到内存,导致你第一次访问的时候会有个页缺失,这个时候kernel才会访问磁盘把数据拿出来,因此你的查询就有一部分时间消耗在这个页缺失上,所以在init函数里,初始化mmap的时候需要加MAP_POPULATE这个参数。这样系统会预加载这些数据到内存中,而这些时间消耗是计算在inittime里的。

另外看了zjx20的代码,证明了zjx20并不是qlcoder的内部人员,shinian这种资深java狗是写不出这个级别的c++代码的。是在下输了。

blahgeek · 2016-09-02 00:40:36

给各位大神跪了…我也来弱弱的分享一下我的思路…:


20号左右的时候看到这个题,很自然的就使用Hash:开一个文件,头部为hash表,每一个hash项指向一个item (item_offset),item为{key_len, value_len, next_item_offset, key[], value[]}。每次Put时,不管是否存在key,直接在文件末尾写入数据,把hash表相应项更新为该offset,把hash表相应项原有值设到next_item_offset(处理碰撞)。Hash函数找了MurmurHash2,很快,而且结果分布很均匀。

文件通过mmap访问,头部hash表一直在内存里,数据部分按需调用mmap/mremap。写的时候需要比较仔细的考虑安全性,比如要先写数据再更新offset等等。

这个版本写完大概就进前十了…当时就开始幻想hhkb的手感了…= =


然后开始优化……:

  • 注意到测试用例的所有key大小是能放在内存里的,于是把一个文件拆成两个,一个存hash和key,用mmap一直放在内存里,一个存value,用read/write读写

  • 再注意到其实内存还是有点空闲,于是把尽可能多的value也放到key后面,放不下了才写到另一个文件

  • Put的时候直接Insert至头部使得Put操作很快,不过导致链条过长,影响Get速度,鉴于init时间是free的,在init的时候进行dedup

  • IO优化:pread/pwrite取代read/write,用fadvise(...FADV_WILLNEED)预读取(在hash匹配但是还没进行key的字符串匹配的时候,很有可能是需要读value的,先让kernel读)

  • Hash前8(16)个字符就够了

  • 评测时没开编译优化,可以直接把自己-Ofast编译的hash函数汇编代码内联进来

  • 每次Get需要init/resize一个string,并且傻逼的string每次init/resize的时候会初始化,于是想办法hack掉直接设置string的length...

在这些科学和不科学的优化搞完之后,当时升到了rank2,然后……就没有然后了 那成为了我在排行榜上最辉煌的一刻… TT


时隔五天再次看排行榜的时候我都震惊了……怎么一个个都刷到了400+w...

一狠心,把key的比较直接去掉,只用hash值比较,终于也上了400w,上升到rank5...(可是心底实在是无法接受这样的实现啊……)

然而接下来,思来想去实在没觉得还有什么点可以有本质上的提升了:IO上没有多余的操作,也没有可以预读取的地方,鉴于操作随机,感觉也没有什么可以缓存的地方,代码自认为写的也还可以了……真心不理解大神们是怎么做到了……


直到今天终于见到了rank1234的代码…总结一下:

  • 区分small/medium/large调参数调参数调参数

  • 不知道为啥,虽然访问应该随机,不过还是有缓存比较好?

  • 面对编译器优化无止境……

  • 自己还是太年轻了…

zjx20 · 2016-09-02 00:48:20

我是8月19号看到的这个比赛。白天上班,只有晚上有时间做一下,所以这十几天几乎每晚都弄到一两点。现在终于告一段落,晚上可以好好睡觉了。

技术方案分析

言归正传,说一下技术。我的方案是“哈希索引+数据文件”,put操作是先把value追加写入数据文件(不管key是否已存在),然后更新索引;get操作则通过索引找到value在数据文件中的位置,然后读取。感觉跟大家的方案大同小异,我就按自己的理解来讲一些要点。

  • 避免随机写。服务器硬盘的特点是顺序读写很快,随机读比较快,随机写则很慢。更新key时也是追加写数据文件,而不是原地更改数据,就能避免随机写。

  • 使用哈希表做索引。综合题目的要求和限制,哈希表是最适合做索引的数据结构,更新和查找的复杂度都是O(1)。为了将哈希表完全放入内存,哈希表的item不能太大,于是通过std::hash()将不定长的key压缩成固定的8字节数据,这样一个哈希表项只需要占16字节。使用std::hash()是一种取巧,如果测试数据中有两个key的hash值冲突的话就容易出错。

  • 使用mmap。索引是通过mmap直接映射到内存的,数据文件则采用滚动mmap的方法写入数据(一次性map整个数据文件会超出内存用量)。使用mmap有两个好处:一是减少系统调用的次数,比如平时读文件的某个部分,要先调lseek()定位文件指针,再调read()读数据,就出现了两次系统调用;而使用mmap读文件,整个过程只有调mmap()的那一次系统调用,所以mmap对性能提升很大。二是map的内存修改是由操作系统负责刷到硬盘,就算程序被kill操作系统也会将数据持久化,除非掉电。正好用来对付题目的kill -9,这也是一个取巧。

  • 多使用内存。在我的实现中,一个数据文件块是64MB,通过mmap映射到内存,再大的话跑小数据就会超内存。如果只映射一块数据文件,则跑大数据的时候就有200MB内存被浪费了。于是我总是将最新的4块文件映射到内存,占256MB,部分get操作会落到这256MB中,可以减少一定数量的读硬盘操作。甚至部分put操作也可以在这块内存上做原地更新,可以让数据文件更加紧凑。

  • 细节优化,压榨性能。这里是指代码上的细节,包括避免分支语句,内联代码,位运算代替求模,字节对齐等等。在比赛后期,技术方案定型了,又没有什么突破的时候,只能靠这些东西来提高一点点分数...

我的代码里面还有一个取巧地方,就是根据数据集调整哈希表大小。本来直接用一个较大的值就可以通过3组数据的,但是测试过程中发现,小一点的哈希表效率更高(这跟我的认知相反,我表示很困惑)。估计是我的哈希表实现有问题...

迭代

当然,我并不是一开始就知道要这样做的,也是经过了很多尝试才得到这个方案,下面来记一记迭代的过程。

  • 第一个版本是用fopen+fread+fwrite+md5,大方向还是“哈希索引+数据文件”,总分只有几万,属9分垫底

  • 然后把fopen系列函数换成了open系列,总分稍微多了点

  • 发现了可以用std::hash()代替md5,不会Wrong Answer,总分又高了一点,代码也少了很多...

  • 想到可以用mmap,就将索引映射进内存,这时总分大概15w+

  • 然后再想到数据文件可以用滚动mmap的方式写入,总分大概25w+

  • 之后是保留4块文件在内存中,优化读操作,总分到32w+

  • 然后到了瓶颈不知道怎么优化,靠调参数和优化细节,勉强把总分提到45w+

  • 最后比赛临结束的时候,想到可以原地更新内存中的数据,借这个优化刷到了47w

另外我还尝试了很多不靠谱的“优化”,也拿出来分享下吧:

  • BloomFilter,刚开始的时候,读写操作还没有做优化,当时引入了BloomFilter来过滤一些读请求,也有一定效果。到了后来读写操作优化比较好了,这个东西反而影响了性能,于是就拿掉了。

  • base64,题目说value的字符集是base64编码的字符集,我就想把value还原成二进制数据,可以减少25%的数据量。实现好了之后发现cpu成了瓶颈...

  • aio,我还尝试过用linux的aio,可能是使用姿势不对,很容易读到老数据就WA了。好不容易调通了,结果性能不比mmap好。估计还是跟系统调用次数有关。

更新

shinian说不明白最后那个刷到47w的优化是什么,我在这里细化一下。前面一开始就强调了写数据文件要以追加的形式写,避免去修改文件的内容,避免随机写,一直以来我都是按这个原则去实现的。但到最后我发现有一种情况可以例外的,如果被更新的内容恰好在那256MB内存中,这时候就可以原地更新,而不需要追加写。请看代码:

void put(const std::string& key, const std::string& value) {
    // ...
    IndexItem* item = xxx;  // 查索引

    if (item->key) {  // key不等于0,表示key已存在
      // 计算原value所在的块号和偏移量
      uint32_t pos = item->pos;
      int seg = (pos >> POS_BITS) & SEG_MASK;
      int real_pos = pos & POS_MASK;
      int aligned_len = (item->len + (sizeof(intptr_t) - 1)) & (~(sizeof(intptr_t) - 1));
      int v_len = value.size();

      // seg + INMEM_SEGS > _n  是判断该块是否在内存中
      // aligned_len >= v_len  是判断原value所占的空间是否能放得下新value
      if (seg + INMEM_SEGS > _n && aligned_len >= v_len) {
        // 更新数据和索引,return
        memcpy(_map_base[seg & INMEM_SEGS_MASK] + real_pos, value.c_str(), v_len);
        item->len = v_len;
        return;
      }
    }

    // 后面就是追加写数据的流程
}

===========

以上是我的分享,如有没讲清楚的地方,欢迎大家找我讨论~

cheyulin · 2016-09-02 19:51:22

我的大数据版本(fstream, index file + value file + naive memory buffer):

  • Small: 125w + 17w

  • Medium: 17w + 8.5w

  • Large: 5w + 1.5w

//
// Created by cheyulin on 8/23/16.
//
#ifndef KEYVALUESTORE_FINAL_VERSION_KEY_VALUE_STORE_H
#define KEYVALUESTORE_FINAL_VERSION_KEY_VALUE_STORE_H

#include <algorithm>
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>
#include "fcntl.h"

constexpr int INT_SIZE = sizeof(int);
#define INDEX_NAME "index.meta"
#define DB_NAME "value.db"
#define unlikely(x) __builtin_expect((x),0)

using namespace std;
string empty_str;
const static string NULL_STR = "NULL";

hash<string> hash_func;

struct key_value_info {
    string key_str_;
    string val_str_;
    int val_index_{0};
    int val_len_{0};
};

class yche_map {
private:
    ifstream db_stream_;
    vector<key_value_info> hash_table_;
    char *value_buffer;
    string result_str_;
    int cur_cached_val_size_{0};
    int max_cached_val_size_{0};
    int max_slot_size_{0};

public:
    yche_map() {
        db_stream_.open(DB_NAME, ios::binary);
        value_buffer = new char[1024 * 32];
        result_str_.reserve(1024 * 32);
    }

    ~yche_map() {
        delete[]value_buffer;
    }

    void set_max_cached_value_size(int size) {
        max_cached_val_size_ = size;
    }

    void resize(int size) {
        hash_table_.resize(size);
        max_slot_size_ = size;
    }

    string get(const string &key) {
        auto index = hash_func(key) % max_slot_size_;
        for (; hash_table_[index].key_str_.size() != 0; index = (index + 1) % max_slot_size_) {
            if (hash_table_[index].key_str_ == key) {
                if (hash_table_[index].val_str_.size() > 0)
                    return hash_table_[index].val_str_;
                else {
                    db_stream_.seekg(hash_table_[index].val_index_, ios::beg);
                    db_stream_.read(value_buffer, hash_table_[index].val_len_);
                    result_str_.assign(value_buffer, 0, hash_table_[index].val_len_);
                    return result_str_;
                }
            }
        }
        return NULL_STR;
    }

    void put(string &key, int value_index, int value_length, string &value = empty_str) {
        auto index = hash_func(key) % max_slot_size_;
        for (; hash_table_[index].key_str_.size() != 0; index = (index + 1) % max_slot_size_) {
            if (hash_table_[index].key_str_ == key) {
                hash_table_[index].val_index_ = value_index;
                hash_table_[index].val_len_ = value_length;
                if (hash_table_[index].val_str_.size() != 0)
                    hash_table_[index].val_str_ = move(value);
                return;
            }
        }
        hash_table_[index].key_str_ = move(key);
        hash_table_[index].val_index_ = value_index;
        hash_table_[index].val_len_ = value_length;

        if (cur_cached_val_size_ < max_cached_val_size_) {
            ++cur_cached_val_size_;
            hash_table_[index].val_str_ = move(value);
        }
    }
};

class Answer {
private:
    yche_map map_;
    ofstream index_stream_;
    ofstream db_stream_;
    int key_len_{0};
    int val_index_{0};
    int val_len_{0};
    int threshold_{0};
    int file_size_{0};
    bool is_init_{false};
    string key_str_;
    string value_str_;

    void init_map() {
        if (val_len_ <= 160) {
            map_.resize(50000);
            map_.set_max_cached_value_size(250000);
        } else if (val_len_ <= 3000) {
            map_.resize(500000);
            map_.set_max_cached_value_size(800000);
            threshold_ = file_size_ + 1;
        }
        else {
            map_.resize(50000);
            map_.set_max_cached_value_size(11000);
            threshold_ = file_size_ + 1;
        }
        is_init_ = true;
    }

public:
    void get_db_file_size() {
        int fd_ = open(DB_NAME, O_RDONLY | O_CREAT, 0600);
        struct stat st;
        fstat(fd_, &st);
        file_size_ = st.st_size;
    }

    void read_file() {
        char *buf_ = new char[32 * 1024];
        ifstream index_stream(INDEX_NAME, ios::binary);
        ifstream db_stream(DB_NAME, ios::binary);
        for (; index_stream.good();) {
            index_stream.read((char *) &key_len_, INT_SIZE);
            index_stream.read(buf_, key_len_);
            if (index_stream.good()) {
                key_str_.assign(buf_, key_len_);
                index_stream.read((char *) &val_index_, INT_SIZE);
                index_stream.read((char *) &val_len_, INT_SIZE);
                if (unlikely(!is_init_))
                    init_map();
                if (val_index_ >= threshold_) {
                    db_stream.seekg(val_index_, ios::beg);
                    db_stream.read(buf_, val_len_);
                    value_str_.assign(buf_, 0, val_len_);
                    map_.put(key_str_, val_index_, val_len_, value_str_);
                }
                else
                    map_.put(key_str_, val_index_, val_len_);
            }
        }
        val_index_ = val_index_ + val_len_;
        delete[]buf_;
    }

    Answer() {
        ios::sync_with_stdio(false);
        get_db_file_size();
        read_file();
        index_stream_.open(INDEX_NAME, ios::app | ios::binary);
        db_stream_.open(DB_NAME, ios::app | ios::binary);
    }

    string get(string key) {
        return map_.get(key);
    }

    void put(string key, string value) {
        val_len_ = value.size();
        key_len_ = key.size();
        if (unlikely(!is_init_))
            init_map();
        index_stream_.write((const char *) &key_len_, INT_SIZE);
        index_stream_.write(key.c_str(), key_len_);
        index_stream_.write((const char *) &val_index_, INT_SIZE);
        index_stream_.write((const char *) &val_len_, INT_SIZE);

        db_stream_.write(value.c_str(), val_len_);

        map_.put(key, val_index_, val_len_, value);
        val_index_ += val_len_;

        index_stream_.flush();
        db_stream_.flush();
    }
};

#endif //KEYVALUESTORE_FINAL_VERSION_KEY_VALUE_STORE_H

snipper · 2016-09-08 11:32:34

medimum没过得辣鸡代码:

#include <stdio.h>
#include <string.h>
#include <memory>
#include <vector>
#include <string>
using namespace std;
const char* IFN = "t.idx";
const char* DFN = "t.dat";
const size_t BKTS = (1u<<20);
const size_t MASK = (1u<<20)-1;
using pos_t = uint32_t;
using len_t = uint16_t;
struct Stub {
    size_t h;
    pos_t kp, vp;
    len_t kl, vl;
    int nx;
};
size_t SOS = sizeof(Stub);
size_t k2hash(const string& k) {
    return hash<string>()(k);
}
size_t h2slot(size_t h) {
    return h & MASK;
}
string vread(FILE* fp, int pos, int len) {
    string s(len, '\0');
    fseek(fp, pos, SEEK_SET);
    fread(&s[0], 1, len, fp);
    return s;
}
class Answer {
    vector<Stub> c_;
    using fptr = unique_ptr<FILE, int(*)(FILE*)>;
public:
    Answer() {
        fptr i(fopen(IFN, "rb+"), fclose);
        if (i) {
            fseek(i.get(), 0, SEEK_END);
            long ts = ftell(i.get()) / SOS;
            c_.reserve(ts);
            c_.resize(ts);
            fseek(i.get(), 0, SEEK_SET);
            fread(&c_[0], SOS, c_.size(), i.get());
        } else {
            i.reset(fopen(IFN, "wb+"));
            fptr d(fopen(DFN, "wb+"), fclose);
            c_.reserve(BKTS);
            c_.resize(BKTS);
            memset(&c_[0], 0, c_.size() * SOS);
            fwrite(&c_[0], SOS, c_.size(), i.get());
        }
    }
    string get(string k) {
        size_t h = k2hash(k);
        size_t slot = h2slot(h);
        fptr i(fopen(IFN, "rb+"), fclose);
        if (i) {
            fptr d(fopen(DFN, "rb+"), fclose);
            for (int p = slot; p > 0 && c_[p].nx; p = c_[p].nx) {
                auto& c = c_[p];
                if (c.h == h && c.kl == k.size() && vread(d.get(), c.kp, c.kl) == k) {
                    return vread(d.get(), c.vp, c.vl);
                }
            }
        }
        return "NULL";
    }
    void put(string k, string v) {
        size_t h = k2hash(k);
        size_t slot = h2slot(h);
        fptr i(fopen(IFN, "rb+"), fclose);
        fptr d(fopen(DFN, "rb+"), fclose);
        if (!c_[slot].nx) {
            fseek(d.get(), 0, SEEK_END);
            pos_t kp = ftell(d.get()); fwrite(&k[0], 1, k.size() + 1, d.get());
            pos_t vp = ftell(d.get()); fwrite(&v[0], 1, v.size() + 1, d.get());
            c_[slot] = {h, kp, vp, k.size(), v.size(), -1};
            fseek(i.get(), slot * SOS, SEEK_SET);
            fwrite(&c_[slot], SOS, 1, i.get());
        } else {
            for (int p = slot; p > 0 && c_[p].nx; p = c_[p].nx) {
                auto& c = c_[p];
                if (c.h == h && c.kl == k.size() && vread(d.get(), c.kp, c.kl) == k) {
                    if (vread(d.get(), c.vp, c.vl) == v) {
                        return;
                    }
                    fseek(d.get(), 0, SEEK_END);
                    c.vp = ftell(d.get());
                    c.vl = v.size();
                    fwrite(&v[0], 1, v.size() + 1, d.get());
                    fseek(i.get(), p * SOS, SEEK_SET);
                    fwrite(&c, SOS, 1, i.get());
                    return;
                }
            }
            fseek(d.get(), 0, SEEK_END);
            pos_t kp = ftell(d.get());
            fwrite(&k[0], 1, k.size() + 1, d.get());
            pos_t vp = ftell(d.get());
            fwrite(&v[0], 1, v.size() + 1, d.get());
            Stub idx{h, kp, vp, k.size(), v.size(), c_[slot].nx};
            int sz = c_.size();
            if (c_.size() == c_.capacity() - 1) {
                c_.reserve(sz + (sz >> 2));
            }
            c_.push_back(idx);
            fseek(i.get(), 0, SEEK_END);
            fwrite(&idx, SOS, 1, i.get());
            c_[slot].nx = sz;
            fseek(i.get(), slot * SOS, SEEK_SET);
            fwrite(&c_[slot], SOS, 1, i.get());
        }
    }
};