test_sha_perf.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. /*
  7. * mbedTLS SHA performance test
  8. */
  9. #include <stdio.h>
  10. #include <stdbool.h>
  11. #include <string.h>
  12. #include "mbedtls/sha256.h"
  13. #include "unity.h"
  14. #include "sdkconfig.h"
  15. #include "esp_heap_caps.h"
  16. #include "test_utils.h"
  17. #include "ccomp_timer.h"
  18. #include "test_mbedtls_utils.h"
  19. TEST_CASE("mbedtls SHA performance", "[aes]")
  20. {
  21. const unsigned CALLS = 256;
  22. const unsigned CALL_SZ = 16 * 1024;
  23. mbedtls_sha256_context sha256_ctx;
  24. float elapsed_usec;
  25. unsigned char sha256[32];
  26. // allocate internal memory
  27. uint8_t *buf = heap_caps_malloc(CALL_SZ, MALLOC_CAP_DMA | MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  28. TEST_ASSERT_NOT_NULL(buf);
  29. memset(buf, 0x55, CALL_SZ);
  30. mbedtls_sha256_init(&sha256_ctx);
  31. ccomp_timer_start();
  32. TEST_ASSERT_EQUAL(0, mbedtls_sha256_starts(&sha256_ctx, false));
  33. for (int c = 0; c < CALLS; c++) {
  34. TEST_ASSERT_EQUAL(0, mbedtls_sha256_update(&sha256_ctx, buf, CALL_SZ));
  35. }
  36. TEST_ASSERT_EQUAL(0, mbedtls_sha256_finish(&sha256_ctx, sha256));
  37. elapsed_usec = ccomp_timer_stop();
  38. free(buf);
  39. mbedtls_sha256_free(&sha256_ctx);
  40. /* Check the result. Reference value can be calculated using:
  41. * dd if=/dev/zero bs=$((16*1024)) count=256 | tr '\000' '\125' | sha256sum
  42. */
  43. const char *expected_hash = "c88df2638fb9699abaad05780fa5e0fdb6058f477069040eac8bed3231286275";
  44. char hash_str[sizeof(sha256) * 2 + 1];
  45. utils_bin2hex(hash_str, sizeof(hash_str), sha256, sizeof(sha256));
  46. TEST_ASSERT_EQUAL_STRING(expected_hash, hash_str);
  47. // bytes/usec = MB/sec
  48. float mb_sec = (CALL_SZ * CALLS) / elapsed_usec;
  49. printf("SHA256 rate %.3fMB/sec\n", mb_sec);
  50. #ifdef CONFIG_MBEDTLS_HARDWARE_SHA
  51. // Don't put a hard limit on software SHA performance
  52. TEST_PERFORMANCE_CCOMP_GREATER_THAN(SHA256_THROUGHPUT_MBSEC, "%.3fMB/sec", mb_sec);
  53. #endif
  54. }