问题描述
我知道,当我在C#中使用DateTime.Now.Ticks它返回一个long值,但我需要将其存储在一个int变量,我很困惑,我是否能保持这种精度。截至目前我只是有一个投
I know that when I use DateTime.Now.Ticks in C# it returns a long value but I need to store it in an int variable and I am confused as to whether or not I can maintain that precision. As of right now I just have a cast
int timeStampValue = (int)DateTime.Now.Ticks;
这是一个项目的约束,所以我知道有失去万吨精度。我想我只是想不出法子做存储在一个int,我可以再比较其他时间戳的时间戳的事情。
This is a project constraint so I understand there is tons of precision lost. I guess I just couldn't think of another way to do a timestamp thing stored in an int that I could then compare to other timestamps.
如何任何建议或意见保持精度,如果可能的话,将不胜感激。
Any suggestions or advice on how to maintain the precision, if possible, would be much appreciated.
每个人的答案是例证。其实我最终只是设立涉及柜台一个过程,当使用一个项目它的计数器设置为0和所有其他计数器加1,那么无论是最高的计数器使用下一个项目。
Everyone's answers were illustrative. I actually ended up just setting up a process involving counters where when an item is used it's counter is set to '0' and all other counters are incremented by 1. Then whatever is the highest counter is the next item to use.
推荐答案
你所需要的所有最显著位? (例如,哪一年)
Do you need all the most-significant bits? (e.g. which year)
你所需要的所有最显著位? (如亚纳秒精度)
Do you need all the least significant bits? (e.g. sub-nanosecond precision)
多久的时间间隔你需要测量过?
How long an interval do you need to measure over?
如果您需要精确到毫秒而已,为什么不失去至少显著位
If you need millisecond precision only, why not lose the least significant bits
int timeStamp = (int)(DateTime.Now.Ticks >> 10) // lose smallest 10 bits
修改
在OP要存储最近使用过的物品的时候:如果这是用户选择的一个用户,你可能什么都不想比第二短!因为有每秒10 ^ 7蜱,有日志(10 ^ 7)/日志(2)=从长远价值23多余位!
edit
the OP wants to store times of recently used items: if this is user selections for a single user, you probably don't want anything shorter than a second! as there are 10^7 ticks per second, there are log(10^7)/log(2)=23 excess bits in the long value!
因此,有多少空间,你需要什么?那么,你的价值观应该注明年,月,日,时,分,秒;有一年约32000000秒=约24位。如果你想存储在过去10年值得加3位。因此,很容易装进一个Int32。
我建议
So how much space do you need? Well, your values ought to specify year, month, day, hour, minute and second; There are about 32 million seconds in a year = about 24 bits. add 3 bits if you want to store the last 10 years worth. So will easily fit into an int32.I'd suggest
int timeStamp = (int)(DateTime.Now.Ticks >>23) // retain bits 23 to 55
这篇关于如何在C#中使用DateTime.Now.Ticks保持精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!