简体   繁体   中英

c# best way to detect time of some action

I tried to do the following:

    public class TimerTest
    {
        private DateTime start;

        public TimerTest()
        {
            start = DateTime.Now;
        }

        public TimerTest(string message)
        {
            Debug.WriteLine("DEBUG: " + message);
        }

        public void Finish(string message)
        {
            var time = DateTime.Now - start;

            var timeWent = String.Format("{0}.{1} sec.", time.Seconds, time.Milliseconds.ToString().PadLeft(3, '0'));

but looks like this is wrong way...

Your constructor overload

public TimerTest(string message)
{
    Debug.WriteLine("DEBUG: " + message);
}

doesn't even initialize the time variable. Did you mean for this constructor to be...

public TimerTest(string message)
{
    Debug.WriteLine("DEBUG: " + message);
    start = DateTime.Now;
}

I believe part of the problem is that you're not instantiating a new start time for every call, so you're just recording the difference from when that time was instantiated.

If you really want to get an accurate reading on the time it takes for code to execute, one of the better options is the Stopwatch class, described here:

https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

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