Created
December 9, 2024 22:45
-
-
Save buybackoff/bcbbc63c071ce295a4620fba509e68b7 to your computer and use it in GitHub Desktop.
Memory Benchmark that is faster to code than to find an app. Gives 24.9 on a machine with 25.6 theoretical limit on a single thread.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MemoryBenchmark | |
{ | |
public static void Run() | |
{ | |
const long sizeGb = 2L; | |
const long arraySize = sizeGb * 1024 * 1024 * 1024; | |
const int elementSize = sizeof(long); | |
long[] data = new long[arraySize / elementSize]; | |
Console.WriteLine($"Allocated {sizeGb}GB array"); | |
Console.WriteLine("Writing to array..."); | |
var stopwatch = Stopwatch.StartNew(); | |
for (long i = 0; i < data.Length; i++) | |
{ | |
data[i] = i; | |
} | |
stopwatch.Stop(); | |
double writeTimeSeconds = stopwatch.Elapsed.TotalSeconds; | |
Console.WriteLine($"Write Time: {stopwatch.ElapsedMilliseconds} ms"); | |
Console.WriteLine("Reading from array..."); | |
stopwatch.Restart(); | |
long sum = 0; | |
var rounds = 100; | |
const int prefetch = 128; | |
const int step = prefetch / elementSize; | |
for (int r = 0; r < rounds; r++) | |
{ | |
for (long i = 0; i < data.Length; i += step) | |
{ | |
sum += data[i]; | |
} | |
} | |
stopwatch.Stop(); | |
double readTimeSeconds = stopwatch.Elapsed.TotalSeconds; | |
Console.WriteLine($"Read Time: {stopwatch.ElapsedMilliseconds} ms"); | |
// Calculate throughput | |
double writeThroughput = arraySize / writeTimeSeconds / (1024 * 1024 * 1024); // GB/s | |
double readThroughput = rounds * arraySize / readTimeSeconds / (1024 * 1024 * 1024); // GB/s | |
Console.WriteLine($"Write Throughput: {writeThroughput:F2} GB/s"); | |
Console.WriteLine($"Read Throughput: {readThroughput:F2} GB/s"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var t1 = Task.Run(() => MemoryBenchmark.Run()); | |
var t2 = Task.Run(() => MemoryBenchmark.Run()); | |
// var t3 = Task.Run(() => MemoryBenchmark.Run()); | |
MemoryBenchmark.Run(); | |
t1.Wait(); | |
t2.Wait(); | |
// t3.Wait(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment