简体   繁体   中英

How can I add a precision within 2 seconds c#

I'm just wondering how I can add a precision of 2 seconds. At the moment my code works how i'd like but I'd like to add a precision of 2000 miliseseconds.

    [TestMethod]
    public void LocationNameSearch()
    {


// Create new stopwatch.
Stopwatch stopwatch = new Stopwatch();

// Begin timing.
stopwatch.Start();

// Import the search method.


    System.Threading.Thread.Sleep(2000);



// Stop timing.
stopwatch.Stop();

//Assert
Assert.IsTrue(stopwatch.ElapsedMilliseconds < 3000, **2000**);


}

If you mean that you want to have a range of 2000 milliseconds over and under a specific value then you could use the following which checks if the elapsed milliseconds are within 2000 milliseconds of 3000.

Assert.IsTrue(stopwatch.ElapsedMilliseconds <= 3000 + 2000
              && stopwatch.ElapsedMilliseconds >= 3000 - 2000
);

Edit: According to the comments it sounds like more of a differentation is needed:

if (stopwatch.ElapsedMilliseconds >= 3000)
{
    if (stopwatch.ElapsedMilliseconds > 5000)
    {
         Assert.Fail("Error");
    }
    else
    {
        // Generate warning
        Assert.Fail("Warning");
    }
}

If you mean the least scale is 2000 then you should do this.

var lowprec = (stopwatch.ElapsedMilliseconds/2000)*2000; // notice the integer division

if(lowprec < 3000)
{
    //pass
}
else if(lowprec < 5000)
{
    //warn
}

Here assume time elapsed is 3542 milliseconds. lowprec becomes 2000 (since its highest precision) and it will pass.

If time elapsed is 4032 milliseconds it lowprec becomes 4000 and then its warning.

But If i were you i would just compare results normally. in programming we dont have 50% true 50% false. it does not make sense. we only have 100% true or 100% false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM