Skip to content

Instantly share code, notes, and snippets.

@norandom
Created February 16, 2024 18:59
Show Gist options
  • Save norandom/24fcae5e65a49909609c1c462f623905 to your computer and use it in GitHub Desktop.
Save norandom/24fcae5e65a49909609c1c462f623905 to your computer and use it in GitHub Desktop.
Quick benchmark - Randomness via CPU
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to convert a byte into its hexadecimal string representation
void byteToHex(unsigned char byte, char hexStr[3]) {
const char hexDigits[] = "0123456789abcdef";
hexStr[0] = hexDigits[byte >> 4]; // Extract the high nibble (4 bits) and find its hex character
hexStr[1] = hexDigits[byte & 0x0F]; // Extract the low nibble and find its hex character
hexStr[2] = '\0'; // Null-terminate the string
}
int main() {
const size_t numIterations = 1000; // Number of times to repeat the process
const size_t numBytes = 1000000; // Number of random bytes to generate per iteration
for (size_t j = 0; j < numIterations; ++j) {
unsigned char* randomBytes = (unsigned char*)malloc(numBytes); // Explicit cast needed here
char* hexString = (char*)malloc(numBytes * 2 + 1); // Each byte -> 2 hex characters, +1 for null terminator, explicit cast needed here
if (!randomBytes || !hexString) {
printf("Memory allocation failed\n");
return 1;
}
// Generate random bytes
for (size_t i = 0; i < numBytes; ++i) {
randomBytes[i] = (unsigned char)(rand() % 256);
}
// Convert bytes to hex string
for (size_t i = 0; i < numBytes; ++i) {
byteToHex(randomBytes[i], &hexString[i * 2]);
}
// Normally, you would do something with hexString here
free(randomBytes);
free(hexString);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment