以 %.7f 格式创建时间戳字符串的更快方法
这是一个我必须以 %.7f 格式创建时间戳字符串的函数。该函数执行仅需 2-3 毫秒。但它是从我的代码中的许多地方调用的,即使优化 1 毫秒,我也会在一个特定的用户操作中节省 1 秒。有什么想法吗?
public static String makeTimestamp()
{
long millis = System.currentTimeMillis();
String result;
Double ts = new Double((millis) / 1000.0);
ByteArrayOutputStream b = new ByteArrayOutputStream();
PrintStream p = new PrintStream(b);
p.printf("%.7f", ts );
result = b.toString();
try
{
p.close();
b.close();
} catch (IOException ioe) {};
return result;
}
This is a function I have to create timestamp string in %.7f format. This function takes only 2-3 ms to execute. But its called from many places in my code, by even optimizing it by 1 ms I will save 1 second in one particular user action. Any ideas?
public static String makeTimestamp()
{
long millis = System.currentTimeMillis();
String result;
Double ts = new Double((millis) / 1000.0);
ByteArrayOutputStream b = new ByteArrayOutputStream();
PrintStream p = new PrintStream(b);
p.printf("%.7f", ts );
result = b.toString();
try
{
p.close();
b.close();
} catch (IOException ioe) {};
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你确实需要它,这比字符串格式化大约快 10 倍:
If you absolutely need it, this is roughly 10 times faster than string formatting:
我不知道它快了多少,但是怎么样
(我不确定为什么我们要在图片中添加双倍)。
I don't know how much faster it is, but how about
(and I am not sure why we bring double into the picture).
根本不清楚为什么要经历 PrintStream 等。有什么问题:
在我的上网本上,每次迭代大约需要 0.04 毫秒...但即使您的原始代码每次迭代也只需要大约 0.1 毫秒。你现在正在运行什么,需要 2-3 毫秒?例如,您是否在调试器中运行?我不明白为什么它会这么慢——我的上网本并不是一台特别快的机器。
尽管所有性能都很重要,但我想说上述方法相对于原始方法的主要好处是简单。原文非常复杂,没有任何充分的理由。
It's not at all clear why you're going through a PrintStream etc. What's wrong with:
On my netbook that takes around 0.04ms per iteration... but even your original code only takes around 0.1ms per iteration. What are you running on that takes 2-3ms at the moment? Are you running in a debugger, for example? I can't understand why it would be so slow - it's not like my netbook is a particularly fast machine.
All performance matters aside though, I'd say the main benefit of the above method over your original is simplicity. The original is very complicated for no good reason at all.