在计算时间问题而采取的执行功能 [英] Problem in calculating time taken to execute a function

查看:159
本文介绍了在计算时间问题而采取的执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到运行功能所花费的时间。我这样做是这样的:

I am trying to find the time taken to run a function. I am doing it this way:

SomeFunc(input) {
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    //some operation on input          

    stopWatch.Stop();

    long timeTaken = stopWatch.ElapsedMilliseconds;
}

现在的中提到的评论上的一些输入操作需要根据输入显著时间 SomeFunc

Now the "some operation on input" as mentioned in the comments takes significant time based on the input to SomeFunc.

现在的问题是,当我打电话 SomeFunc 从主多次,我得到timeTaken正确只在第一次,而其余的时间就被分配到0是否有上述code的一个问题?

The problem is when I call SomeFunc multiple times from the main, I get timeTaken correctly only for the first time, and the rest of the time it is being assigned to 0. Is there a problem with the above code?

编辑: 有多个文本字段的UI,并且单击按钮时,它被委托给SomeFunc。所述SomeFunc使得基于输入(从文本字段)一些计算,并显示在UI上的结果。我不能在输入一些操作共享code,因为我已经签署了保密协议。不过,我可以回答你的问题是什么我想达到那里。请大家帮帮忙。

There is a UI with multiple text fields, and when a button is clicked, it is delegated to the SomeFunc. The SomeFunc makes some calculations based on the input (from the text fields) and displays the result on the UI. I am not allowed to share the code in "some operation on input" since I have signed an NDA. I can however answer your questions as to what I am trying to achieve there. Please help.

编辑2: 因为它似乎,我越来越怪异值当函数被调用的第一次,并作为@Mike Bantegui提到的,​​必须有JIT优化回事,唯一的解决办法我现在能想到的(拿不到零执行时间)是,显示在纳秒的时间。怎么可能显示在纳米秒的时间在C#?

EDIT 2: As it seems that I am getting weird value when the function is called the first time, and as @Mike Bantegui mentioned, there must be JIT optimization going on, the only solution I can think of now (to not get zero as execution time) is that to display the time in nano seconds. How is it possible to display the time in nano seconds in C#?

推荐答案

其实你得到了错误的时间,在第一次启动和正确的时间剩余。 您不能中继只是在第一次调用来测量时间。然而,接缝是该操作是太快,所以你得到的 0 的结果。要正确测量测试调用函数1000次例如看平均成本时间:

In fact you are getting the wrong time at the first start and correct time to the remaining. You can't relay just on the first call to measure the time. However It seams to be that the operation is too fast and so you get the 0 results. To measure the test correctly call the function 1000 times for example to see the average cost time:

Stopwatch watch = StopWatch.StartNew();
for (int index = 0; index < 1000; index++)
{
    SomeFunc(input);
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);

编辑:

怎么可能显示在纳米秒的时间

How is it possible to display the time in nano seconds

您可以得到 watch.ElapsedTicks 键,然后将其转换为纳秒:(watch.ElapsedTicks / Stopwatch.Frequency)*十亿

You can get watch.ElapsedTicks and then convert it to nanoseconds : (watch.ElapsedTicks / Stopwatch.Frequency) * 1000000000

这篇关于在计算时间问题而采取的执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆