Skip to content

Instantly share code, notes, and snippets.

@cgwalters
Last active March 3, 2023 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgwalters/169349fd1c06fd4fb4d3a7ce33303222 to your computer and use it in GitHub Desktop.
Save cgwalters/169349fd1c06fd4fb4d3a7ce33303222 to your computer and use it in GitHub Desktop.
Benchmark OpenSSL SHA256 vs GLib
/*
$ gcc -O2 $(pkg-config --cflags --libs openssl glib-2.0) -Wall -o sha256-bench-openssl sha256-bench-openssl.c
$ ./sha256-bench-openssl
openssl: 3900 msec
glib: 7950 msec
speedup: 2.04
$
*/
#define _GNU_SOURCE 1
#include <stdio.h>
#include <sys/xattr.h>
#include <sys/types.h>
#include <string.h>
#include <sys/stat.h>
#include <assert.h>
#include <fcntl.h>
#include <err.h>
#include <openssl/evp.h>
#include <glib.h>
int
main (int argc, char **argv)
{
unsigned int len;
unsigned char openssl_raw_checksum[EVP_MAX_MD_SIZE];
unsigned char gchecksum_raw[32];
EVP_MD_CTX *ctx;
char buf[16384];
guint64 start, end;
guint64 openssl_elapsed;
guint64 glib_elapsed;
const int count = 100000;
memset (buf, 0x1, sizeof (buf));
ctx = EVP_MD_CTX_create();
assert (ctx);
assert (EVP_DigestInit_ex(ctx, EVP_sha256(), NULL));
start = g_get_monotonic_time ();
for (int i = 0; i < count; i++)
assert (EVP_DigestUpdate(ctx, buf, sizeof (buf)));
end = g_get_monotonic_time ();
openssl_elapsed = (end - start)/1000;
assert (EVP_DigestFinal_ex(ctx, openssl_raw_checksum, &len));
EVP_MD_CTX_destroy(ctx);
GChecksum *gchecksum = g_checksum_new (G_CHECKSUM_SHA256);
start = g_get_monotonic_time ();
for (int i = 0; i < count; i++)
g_checksum_update (gchecksum, (unsigned char *)buf, sizeof (buf));
end = g_get_monotonic_time ();
glib_elapsed = (end - start)/1000;
g_assert (memcmp (openssl_raw_checksum, gchecksum_raw, 32));
g_print ("openssl: %" G_GUINT64_FORMAT " msec\n", openssl_elapsed);
g_print ("glib: %" G_GUINT64_FORMAT " msec\n", glib_elapsed);
g_print ("speedup: %0.2f\n", ((double)glib_elapsed)/openssl_elapsed);
return 0;
}
@ddjerqq
Copy link

ddjerqq commented Mar 3, 2023

what do you mean by msec? million per second?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment