是否可以使用Environment.TickCount
来计算时间跨度?
int start = Environment.TickCount;
// Do stuff
int duration = Environment.TickCount - start;
Console.WriteLine("That took " + duration " ms");
因为TickCount
是带符号的,并将在25天后滚动(它需要50天才能达到所有32位,但如果你想弄明白任何数学意义,你必须删除有符号的位),它看起来太冒险了,没有用。
我使用的是DateTime.Now
。这是最好的方法吗?
DateTime start = DateTime.Now;
// Do stuff
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("That took " + duration.TotalMilliseconds + " ms");
发布于 2020-07-12 19:23:14
溢出补偿
如前所述,翻转可能发生在24.9天之后,或者,如果您使用uint cast,则可能发生在49.8天之后。因为我不想pInvoke GetTickCount64,所以我写了这个溢出补偿。示例代码使用'byte‘来保持数字的便捷性。请看一看,里面可能还是有错误:
using System;
namespace ConsoleApp1 {
class Program {
//
static byte Lower = byte.MaxValue / 3;
static byte Upper = 2 * byte.MaxValue / 3;
//
///<summary>Compute delta between two TickCount values reliably, because TickCount might wrap after 49.8 days.</summary>
static short Delta( byte next, byte ticks ) {
if ( next < Lower ) {
if ( ticks > Upper ) {
return (short) ( ticks - ( byte.MaxValue + 1 + next ) );
}
}
if ( next > Upper ) {
if ( ticks < Lower ) {
return (short) ( ( ticks + byte.MaxValue + 1 ) - next );
}
}
return (short) ( ticks - next );
}
//
static void Main( string[] args ) {
// Init
Random rnd = new Random();
int max = 0;
byte last = 0;
byte wait = 3;
byte next = (byte) ( last + wait );
byte step = 0;
// Loop tick
for ( byte tick = 0; true; ) {
//
short delta = Delta( next, tick );
if ( delta >= 0 ) {
Console.WriteLine( "RUN: last: {0} next: {1} tick: {2} delta: {3}", last, next, tick, delta );
last = tick;
next = (byte) ( last + wait );
}
// Will overflow to 0 automatically
step = (byte) rnd.Next( 0, 11 );
tick += step;
max++; if ( max > 99999 ) break;
}
}
}
}
https://stackoverflow.com/questions/243351
复制相似问题