【发布时间】:2014-04-03 13:17:45
【问题描述】:
我需要定期将数十亿个 DateTimes 从 UTC 转换为 EDT。
TimeZoneInfo.ConvertTime 非常方便,但非常非常慢。
我将其比作 TimeSpan 的简单减法。请参阅下面的 SSCCE。
如果您注释掉 OPTION 1 或 OPTION 2(显示在代码中),您将看到截然不同的运行时间。
我想要该功能,但需要更快的速度有没有办法做到这一点?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
namespace BinTest2
{
public partial class Form1 : Form
{
static TimeZoneInfo edtZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
static TimeZoneInfo gmtZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
static TimeZoneInfo utcZone = TimeZoneInfo.FindSystemTimeZoneById("UTC");
public static CultureInfo ci = CultureInfo.InvariantCulture;
private void button5_Click(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
DateTime DT = new DateTime(2013,01,01);
DateTime TDT;
TimeSpan TS = new TimeSpan(4,0,0);
for (int i = 0; i < 100000000; i++)
{
//TDT = DT - TS; //OPTION 1
TDT = TimeZoneInfo.ConvertTime(DT, utcZone, edtZone); //OPTION 2
}
sw.Stop();
label1.Text = "Time taken: " + sw.ElapsedMilliseconds ;
}
}
}
【问题讨论】:
-
你不能为你做一个选项 1 的辅助方法吗?这对我来说似乎是两全其美。
-
问题是不同日期的时区变化。 TimeZoneInfo 负责所有这些
-
说选项 1“更快”并不公平,因为这两个选项做不同的事情(正如您所指出的,选项 1 不考虑夏令时)
-
这些基准测试的运行时间是多少?
-
运行一亿次可以让任何代码变慢。 ConvertTime() 后面有相当多的时间,但在我的笔记本电脑上它仍然只需要 0.5 微秒。当它需要大约 800 个 CPU 周期时,没有太大的改进空间。这应该使程序阅读倍的瓶颈,I/O往往是真正的限制因素。读取数十亿条 dbase 记录或文本文件行需要一段时间。