1

I want to measure time memory allocation using this code:

long AForMemory = DateTime.Now.Ticks;
double[] massDoubleForMemory = new double[num];
long BForMemory = DateTime.Now.Ticks;
long rezult = BForMemory - AForMemory;

But, no matter how much is num(100k or 1M), rezult = 0 or 10001 (randomly). Why? Or is it correct way to measure?

  • What benefit would you have from measuring this? It's not something you can affect in any way. – vgru Mar 29 '12 at 08:22

2 Answers2

0

DateTime is not precise enough to meassure such small time gaps. You can use a stopwatch for that from the System.Diagnostics namespace

int num = 1024 * 1024;
Stopwatch sw = new Stopwatch();
sw.Start();
long AForMemory = DateTime.Now.Ticks;
double[] massDoubleForMemory = new double[num];
sw.Stop();
long elapsed = sw.ElapsedTicks;

If your attempt is to diagnose the impact that certain types of allocations have, then you're very likely looking at the wrong place. Allocation in .NET can be very fast or very slow. If an allocation is preceded by a garbage collection for example or a new memory block needs to be reserved by the garbage collector to satisfy your request, the request itself might take a long time compared to when the gc collector has enough space available. The GC is dynamic in a way that it can determine anytime to do some heavy operations.

Apart from that, the real performance problems come with garbage collections, not allocations.

Polity
  • 14,734
  • 2
  • 40
  • 40
0

It's quite possibly a correct measure of the time. Allocating memory isn't really representable in the O(x) form people are used to; the size of the block doesn't really change the allocation time, if the amount of memory is available, it's allocated.

For a more elaborate and well-written answer, see this question: Time complexity of memory allocation

But for future reference you may want to investigate the 'System.Diagnostics.StopWatch' class, it contains some nice methods for measuring elapsed time. http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

Community
  • 1
  • 1
Jason Larke
  • 5,289
  • 25
  • 28