1

我正在使用khash.h库进行散列。我想检查插入 100 万个密钥后它消耗了多少内存。

这是代码。

https://github.com/attractivechaos/klib/blob/master/khash.h

我想要什么:我在此表中输入 n 个唯一条目。在插入键和值之后,我想检查这个 hastable 消耗了多少空间。

问题:输入 1000 条目后的示例。当我尝试使用kh_size(h)给出的函数获取哈希表的大小时,khash.h我只得到 387 个条目。但是当我试图通过给出我能够获得的密钥来获得价值时。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include "khash.h"
#include "string.h"

#define kh_get_val(kname, hash, key, defVal) ({k=kh_get(kname, hash, key);(k!=kh_end(hash)?kh_val(hash,k):defVal);})
#define kh_set(kname, hash, key, val) ({int ret; k = kh_put(kname, hash,key,&ret); kh_value(hash,k) = val; ret;})

const int khIntInt = 33;

KHASH_MAP_INIT_INT(khIntInt, long long) // setup khash to handle string key with int payload

int int_key_int_body_example(char *filename) {
    printf("\n\nBegin khash test string key with int payload\n");
    int ret, is_missing;
    khiter_t k;
    char *tval;
    khash_t(khIntInt) *h = kh_init(khIntInt); // create a hashtable
    printf("\n --------------------------------- FILE READ AND WRITE OPERTAION -------------------\n");

    FILE *fp;
    int * ch;
    char line[200];
    fp = fopen(filename,"r");
    if (!fp) {
        perror("could not find the file");
        exit(0);
    }

    printf("\n ------------------------------------------------- PUTTING ALL KEYS ---------------------\n");

    int count = 0;
    long long val_line = 0;
    while (fgets(line, 200, fp) != NULL ) {
        printf(" Trying to Add key = %s and value = %s count =%lu \n",
               line, line, count++);
        val_line = strtoll(line, NULL, 0);
        printf("\n int_key_int_body: Here is the value in integer After Atoi = %ld \n", val_line);
        kh_set(khIntInt, h, val_line, val_line);
        printf(" ### DEBUG: h->n_buckets=%d,h->size=%d,h->n_occupied=%d,h->upper_bound=%d \n ",
               h->n_buckets, h->size, h->n_occupied, h->upper_bound);
    }
    fseek(fp, 0, SEEK_SET);
    printf("\n ------------------------------------------------- GETTING ALL VALUES ---------------------\n");
    count = 0;
    while (fgets(line, 200, fp) != NULL) {
        val_line = strtoll(line, NULL, 0);
        printf("\n int_key_int_body: Here is the value in integer After Atoi = %ld \n",val_line);
        k = kh_get(khIntInt, h, val_line);
        if (k == kh_end(h)) {
            printf("no key found for line=%ld", val_line);
        } else {
            printf("GET value for  key = %s and value = %d count =%lu and k_iterator=%d \n",
                   line, kh_val(h, k), count++, k);
        }
    }
    printf("\n ------------------------------------------------- ---------------------\n");
    kh_destroy(khIntInt, h);
    return 0;
}

int main( int argc, char *argv[]) {
    char *filename;
    filename = argv[1];
    printf("\n filename=%s", filename);
    int_key_int_body_example(filename);
}
4

0 回答 0