Search code examples
c#stopwatch

StopWatch and 0 milliseconds via c#


I try to calculate time between operations. So,write two methods with equal code ,but use different ways. At first way i do like that:

private static void calcAverageTimeUid(ISomeObject someObj, int N,ISnapshot _Snapshot)
    {
        Stopwatch stopWatch = new Stopwatch();
        int averageTime = 0;
        var uid = someObj.Uid;

        for (int i = 0; i < N; i++)
        {
            stopWatch.Start();
            var coll = _Snapshot.GetObject(uid);
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            averageTime = averageTime + ts.Milliseconds;
        }
        averageTime = averageTime / N;

    }

And i have result averageTime such as 500 milliseconds. N=1000000 and more.

But , i rewrite this method to two methods: mainCalc ,wich should contains come other methods,f.e. to get average time of uid,id,name and so on.

mainCalc:

private static void mainCalc(ISomeObject someObj,int N,ISnapshot _Snapshot)
    {

        int averageTimeUID = 0;
        for (int i = 0; i < N; i++)
        {
            var tmp=calcAverageTimeUid2(someObj,N,_Snapshot);
            averageTimeUID+=tmp;
        }
        averageTimeUID = averageTimeUID / N;
    }

And other method:

private static int calcAverageTimeUid2(ISomeObject someObj,int N,ISnapshot _Snapshot)
    {
        Stopwatch stopWatch = new Stopwatch();
        var prop = someObj.Uid;
        stopWatch.Start();
        var obj = _Snapshot.GetObject(prop);
        stopWatch.Stop();
        TimeSpan ts = stopWatch.Elapsed;
        return ts.Milliseconds;
    }

So, i run mainCalc and run calcAcerageTimeUid2 in this method.And result of stopWatch=0 milliseconds!

It is wrong result or not? I dont understand-what way of use stopWatch right?

P.S. delete one of excess StopWatch.

P.P.S. Thank all of you!


Solution

  • Milliseconds is not TotalMilliseconds.

    Milliseconds is the entire number of milliseconds of the TimeSpan. Not the total milliseconds which is a double, so you are losing the precision under 1ms.

    And why do you return an int, instead of the TimeSpan?

    Try this code :

    private static void mainCalc(ISomeObject someObj, int N, ISnapshot _Snapshot)
    {
        var averageTimeUID = TimeSpan.Zero;
        for (int i = 0; i < N; i++)
        {
            averageTimeUID += calcAverageTimeUid2(someObj,N,_Snapshot);
        }
        averageTimeUID = new TimeSpan( averageTimeUID.Ticks / N );
    }
    

    The other method:

    private static TimeSpan calcAverageTimeUid2(ISomeObject someObj, int N, ISnapshot _Snapshot)
    { 
        var stopWatch = new Stopwatch();
        var prop = someObj.Uid;
        stopWatch.Start();
        var obj = _Snapshot.GetObject(prop);
        stopWatch.Stop();
        return stopWatch.Elapsed;
    }