S
S
Sergey2021-03-30 19:12:36
.NET
Sergey, 2021-03-30 19:12:36

How to measure RAM from a C# program?

Good afternoon.
I decided to fill the computer's memory in a loop using the code below. I expected the program to throw an OutOfMemoryException and save the amount of allocated memory to a file. But it was not there. The program works and works "allocating" incredible amounts of ram. Stopped at 1024000.
Did I count something wrong? Or is dotnet doing something cunningly? How does it work?

var mem = List<byte[]>();  //каждый элемент списка ==  byte[1024*1024] == 1Mb
while (true)
                {
                    try
                    {
                        if(mem.Count % 1024 == 0)
                        {
                            sizelog(mem.Count); // запись размера в файл
                        }
                        mem.Add(new byte[1024*1024]); // 1Mb выделяется в память
                    }
                    catch (OutOfMemoryException)
                    {
                        sizelog(mem.Count);
                    }
                    
                }


Upd. Ran something like this recursively,
public static void runTestRec(int count)
        {
            try
            {
                var Mb = new byte[1024*1024];
                count ++;
                if(count % (1024) == 0)
                {
                    sizelog(count);
                }
                
            }
            catch (OutOfMemoryException)
            {
                sizelog(count);
            }
            runTestRec(count);
   }


Crashed on 64Gb, still does not converge. I only have 16Gb.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2021-03-30
@gbg

The operating system will not touch the physical memory until something is actually written to it - you can allocate as much as you like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question