qemu/tests/benchmark-crypto-hmac.c
<<
>>
Prefs
   1/*
   2 * QEMU Crypto hmac speed benchmark
   3 *
   4 * Copyright (c) 2017 HUAWEI TECHNOLOGIES CO., LTD.
   5 *
   6 * Authors:
   7 *    Longpeng(Mike) <longpeng2@huawei.com>
   8 *
   9 * This work is licensed under the terms of the GNU GPL, version 2 or
  10 * (at your option) any later version.  See the COPYING file in the
  11 * top-level directory.
  12 */
  13#include "qemu/osdep.h"
  14#include "crypto/init.h"
  15#include "crypto/hmac.h"
  16
  17#define KEY "monkey monkey monkey monkey"
  18
  19static void test_hmac_speed(const void *opaque)
  20{
  21    size_t chunk_size = (size_t)opaque;
  22    QCryptoHmac *hmac = NULL;
  23    uint8_t *in = NULL, *out = NULL;
  24    size_t out_len = 0;
  25    double total = 0.0;
  26    struct iovec iov;
  27    Error *err = NULL;
  28    int ret;
  29
  30    if (!qcrypto_hmac_supports(QCRYPTO_HASH_ALG_SHA256)) {
  31        return;
  32    }
  33
  34    in = g_new0(uint8_t, chunk_size);
  35    memset(in, g_test_rand_int(), chunk_size);
  36
  37    iov.iov_base = (char *)in;
  38    iov.iov_len = chunk_size;
  39
  40    g_test_timer_start();
  41    do {
  42        hmac = qcrypto_hmac_new(QCRYPTO_HASH_ALG_SHA256,
  43                                (const uint8_t *)KEY, strlen(KEY), &err);
  44        g_assert(err == NULL);
  45        g_assert(hmac != NULL);
  46
  47        ret = qcrypto_hmac_bytesv(hmac, &iov, 1, &out, &out_len, &err);
  48        g_assert(ret == 0);
  49        g_assert(err == NULL);
  50
  51        qcrypto_hmac_free(hmac);
  52
  53        total += chunk_size;
  54    } while (g_test_timer_elapsed() < 5.0);
  55
  56    total /= 1024 * 1024; /* to MB */
  57
  58    g_print("hmac(sha256): ");
  59    g_print("Testing chunk_size %ld bytes ", chunk_size);
  60    g_print("done: %.2f MB in %.2f secs: ", total, g_test_timer_last());
  61    g_print("%.2f MB/sec\n", total / g_test_timer_last());
  62
  63    g_free(out);
  64    g_free(in);
  65}
  66
  67int main(int argc, char **argv)
  68{
  69    size_t i;
  70    char name[64];
  71
  72    g_test_init(&argc, &argv, NULL);
  73    g_assert(qcrypto_init(NULL) == 0);
  74
  75    for (i = 512; i <= (64 * 1204); i *= 2) {
  76        memset(name, 0 , sizeof(name));
  77        snprintf(name, sizeof(name), "/crypto/hmac/speed-%lu", i);
  78        g_test_add_data_func(name, (void *)i, test_hmac_speed);
  79    }
  80
  81    return g_test_run();
  82}
  83