你如何将秒表刻度转换为纳秒,毫秒和秒?

时间:2010-02-24 20:04:31

标签: c#

这是一个非常基本的问题......非常令人尴尬,但这里有:

我在C#代码中有一个秒表块。我以刻度确定经过的时间,然后想要转换为ns,ms,s。我知道频率由秒表类提供,并且它是转换所必需的。

由于

6 个答案:

答案 0 :(得分:81)

Stopwatch.Elapsed是TimeSpan,因此您可以执行myStopwatch.Elapsed.TotalMillisecondsmyStopwatch.Elapsed.TotalSeconds等。

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

// Begin timing
stopwatch.Start();

// Do something
for (int i = 0; i < 1000; i++)
{
    Thread.Sleep(1);
}

// Stop timing
stopwatch.Stop();

// Write result
Console.WriteLine("Time elapsed (s): {0}", stopwatch.Elapsed.TotalSeconds);
Console.WriteLine("Time elapsed (ms): {0}", stopwatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Time elapsed (ns): {0}", stopwatch.Elapsed.TotalMilliseconds * 1000000);

<强>输出:

Time elapsed (s): 2.4976622
Time elapsed (ms): 2497.6622
Time elapsed (ns): 2497662200

注意 stopwatch.ElapsedMilliseconds返回long,因此只能精确到毫秒,而stopwatch.Elapsed.TotalMilliseconds则返回double具有与stopwatch.ElapsedTicks相同的精度,除了它更容易使用。 ILSpy表明TimeSpan.TotalMilliseconds无论如何都是使用滴答计算的。

答案 1 :(得分:53)

根据MSDN,频率告诉您每秒的滴答数。因此:

Stopwatch sw = new Stopwatch();
// ...
double ticks = sw.ElapsedTicks;
double seconds = ticks / Stopwatch.Frequency;
double milliseconds = (ticks / Stopwatch.Frequency) * 1000;
double nanoseconds = (ticks / Stopwatch.Frequency) * 1000000000;

答案 2 :(得分:18)

Stopwatch.Frequency为您提供滴答/秒。

所以,如果你有蜱虫,你可以按频率除以获得秒数:

long ticks = sw.ElapsedTicks;
double ns = 1000000000.0 * (double)ticks / Stopwatch.Frequency;
double ms = ns / 1000000.0;
double s = ms / 1000;

例如,你可以这样做:

static void Main()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    System.Threading.Thread.Sleep(3456);
    sw.Stop();

    long ticks = sw.ElapsedTicks;
    double ns = 1000000000.0 * (double)ticks / Stopwatch.Frequency;
    double ms = ns / 1000000.0;
    double s = ms / 1000;

    Console.WriteLine("{0}, {1}, {2}", ns, ms, s);
    Console.ReadKey();
}

在我的系统中,打印:

3455650175.58075, 3455.65017558075, 3.45565017558075

答案 3 :(得分:7)

使用此课程:

public static class Utility
{
    public static long ElapsedNanoSeconds(this Stopwatch watch)
    {
         return watch.ElapsedTicks * 1000000000 / Stopwatch.Frequency;
    }
    public static long ElapsedMicroSeconds(this Stopwatch watch)
    {
        return watch.ElapsedTicks * 1000000 / Stopwatch.Frequency;
    }
}

然后你就可以得到经过的纳秒/微秒:

var stopwatch = Stopwatch.StartNew();
//... measured code part
Console.WriteLine(stopwatch.ElapsedNanoSeconds());
// OR
Console.WriteLine(stopwatch.ElapsedMicroSeconds());

毫秒可以使用秒表的ElapsedMilliseconds()方法。

答案 4 :(得分:5)

来自MSDN docs

使用FrequencyIsHighResolution字段来确定秒表计时实施的精度和分辨率。

long frequency = Stopwatch.Frequency;
Console.WriteLine("  Timer frequency in ticks per second = {0}",
    frequency);
long nanosecPerTick = (1000L*1000L*1000L) / frequency;
Console.WriteLine("  Timer is accurate within {0} nanoseconds", 
    nanosecPerTick);

答案 5 :(得分:2)

使用Elapsed属性:

stopwatch.Elapsed.TotalMilliseconds