Jak zmierzyć czas działania funkcji?

Chcę zobaczyć, jak długo działa funkcja. Więc dodałem obiekt timer w moim formularzu i wyszedłem z tym kodem:

private int counter = 0;

// Inside button click I have:
timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Stop();

I:

private void timer_Tick(object sender, EventArgs e)
{
    counter++;
    btnTabuSearch.Text = counter.ToString();
}
Ale to niczego nie liczy. Dlaczego?
Author: Venkat, 2012-04-11

10 answers

Aby uniknąć przyszłych problemów z timerem, oto odpowiedni kod:

timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 1; //set interval on 1 milliseconds
timer.Enabled = true; //start the timer
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Enabled = false; //stop the timer

private void timer_Tick(object sender, EventArgs e)
{
   counter++;
   btnTabuSearch.Text = counter.ToString();
}
/ Align = "left" / Musisz użyć stopera (System.Diagnostyka) klasa, ponieważ jest to Zegar wysokiej rozdzielczości i słowo Diagnostyka mówi wszystko.

Więc spróbuj tego:

Stopwatch timer = Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

timer.Stop();  
TimeSpan timespan = timer.Elapsed;

btnTabuSearch.Text = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10);
 43
Author: Omar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-31 17:19:44

Nie używaj timera-użyj Stopwatch klasy.

var sw = new Stopwatch();
Result result = new Result();

sw.Start();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

sw.Stop();

// sw.Elapsed tells you how much time passed
 43
Author: Oded,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-11 13:44:08

Powinieneś użyć klasy stopera do funkcji pomiaru czasu.

Spróbuj:

private int counter = 0;

// setup stopwatch and begin timing
var timer = System.Diagnostics.Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

// stop timer and get elapsed time
timer.Stop();
var elapsed = timer.Elapsed;

// display result time
MessageBox.Show(elapsed.ToString("mm':'ss':'fff"));
 11
Author: james lewis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-29 15:23:09

Najlepszym sposobem, aby sprawdzić, jak długo bit kodu trwa, jest użycie System.Diagnostics.Stopwatch.

Oto przykład:

using System.Diagnostics;

#if DEBUG
     Stopwatch timer = new Stopwatch();
     timer.Start();
#endif

     //Long running code

#if DEBUG
     timer.Stop();
     Debug.WriteLine("Time Taken: " + timer.Elapsed.TotalMilliseconds.ToString("#,##0.00 'milliseconds'"));
#endif

Używam #if DEBUG, aby upewnić się, że kod stopera nie dostanie się do wersji produkcyjnej, ale można się bez niego obejść.

 10
Author: Alain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-11 13:43:55

Visual Studio 2015, 2017 Professional i Enterprise ma Narzędzie Diagnostyczne. Jeśli na końcu funkcji znajduje się punkt przerwania, wyświetli on czas i czas trwania w zakładce zdarzenia , Jak pokazano na obrazku:

Tutaj wpisz opis obrazka

Możesz zobaczyć Artykuł Narzędzia diagnostyczne okno debuggera w Visual Studio 2015 Po Więcej Szczegółów.

PS; do tej pory tylko Xamarin forms, cross platform project nie obsługuje tej funkcji. I wish that Microsoft wprowadza tę wspaniałą funkcję również dla projektów formularzy xamarin.

 9
Author: batmaci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-15 16:22:27

Użyj stopera Systemu.Diagnostyka:

static void Main(string[] args)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    Thread.Sleep(10000);
    stopWatch.Stop();

    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;

    // Format and display the TimeSpan value.
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
}
 7
Author: Nikhil Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-22 11:09:59

Dla funkcji timing należy użyć klasy stopera

Również, powodem, dla którego twój timer nie liczy, jest to, że nie ustawiłeś dla niego interwału.

 6
Author: Matt Burland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-11 13:44:16

Być może mógłbyś napisać taką metodę:

public static void Time(Action action)
{
    Stopwatch st = new Stopwatch();
    st.Start();
    action();
    st.Stop();
    Trace.WriteLine("Duration:" + st.Elapsed.ToString("mm\\:ss\\.ff"));
}

I używaj go w ten sposób:

Time(()=>
{
 CallOfTheMethodIWantToMeasure();
});
 4
Author: Philippe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-23 16:05:24

Przejrzałem i zgodziłem się ze wszystkimi sugestiami. Ale chcieliśmy udostępnić jedną ogólną implementację dla execution time logger, gdzie nie chcemy implementować logiki stopera wiele razy, ale nadal chcemy mierzyć czas wykonania dla wielu metod.

Głównym powodem nie implementowania loggera w sposób ogólny jest-wykonywanie metody jest pomiędzy stoperem.Start() i stoper.Stop() również możemy wymagać wyniku metody po wykonaniu do dalszego przetwarzania.

Więc do rozwiązanie tego problemu stworzyłem po przykładowej implementacji, gdzie czas wykonania jest rejestrowany oddzielnie bez mieszania go z rzeczywistym przepływem metody.

public static class Helper
{
    public static T Time<T>(Func<T> method, ILogger log)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        var result = method();
        stopwatch.Stop();
        log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds));
        return result;
    }
}

public class Arithmatic
{
    private ILogger _log;
    public Arithmatic(ILogger log)//Inject Dependency
    {
        _log = log;
    }

    public void Calculate(int a, int b)
    {
        try
        {
            Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging
            Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging
        }
        catch (Exception ex)
        {
            _log.Error(ex.Message, ex);
        }
    }

    private string AddNumber(int a, int b)
    {
        return "Sum is:" + (a + b);
    }

    private string SubtractNumber(int a, int b)
    {
        return "Subtraction is:" + (a - b);
    }
}

public class Log : ILogger
{
    public void Info(string message)
    {
        Console.WriteLine(message);
    }

    public void Error(string message, Exception ex)
    {
        Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace);
    }
}

public interface ILogger
{
    void Info(string message);
    void Error(string message, Exception ex);
}

Wywołanie Części:

 static void Main()
 {
    ILogger log = new Log();
    Arithmatic obj = new Arithmatic(log);
    obj.Calculate(10, 3);
    Console.ReadLine();
 }
 1
Author: Sumit Deshpande,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-02 03:17:08

Zapisz czas, kiedy bieżący krok zaczyna przetwarzać

DateTime dtStart = DateTime.Now;

//Calculate the total number of milliseconds request took (Timespan = to represent the time interval)-> current - started time stamp ...
//TotalMilliseconds -->Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
// to measure how long a function is running 
var result=((TimeSpan)(DateTime.Now - dtStart)).TotalMilliseconds.ToString("#,##0.00") + "ms";
 1
Author: Harshit Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-22 12:23:33