【问题标题】:Luxon: faster calculation of fractional dayLuxon:更快地计算小数天
【发布时间】:2022-08-03 23:48:42
【问题描述】:

我需要计算小数天:自午夜以来经过的一天的小数部分。我还需要任意时间的年月。这些需要在 UTC 时间的上下文中。我的应用程序使用 Luxon,因此我使用以下方法来计算它们,从 DateTime.now() 开始作为任意示例:

const luxonNow = DateTime.now();
const gt = luxonNow.setZone(\'utc\');
const luxonY = gt.year;
const luxonM = gt.month;
const luxonMidnight = gt.startOf(\'day\');
// Create an Interval beginning at midnight, ending now
// Find the decimal hours that have passed. Divide by 24 to find the fractional day passed
const luxonFrac = Interval.fromDateTimes(luxonMidnight, gt).length(\'hours\') / 24;
luxonT = gt.day + luxonFrac;

这是在性能很重要的代码领域。代码速度很快:基准测试表明它最多需要 0.3 毫秒,平均 0.1 毫秒。

我可以让它更快吗?

    标签: luxon


    【解决方案1】:

    主要瓶颈是.setZoneInterval.fromDateTimes().length()。 Luxon 旨在合并时区:这两种方法都需要等待 Intl API 返回结果here,以便在创建DateTime 期间可以定义正确的时区。

    原生 Date 对象支持转换为 UTC。由于这种需要重于数学而轻于定义本地时区的需要,因此可以使用本机 Date 对象来实现相同的结果:

    const dtNow = luxonNow.toJSDate();
    // Get UTC version of date
    const utc = new Date(
      dtNow.getUTCFullYear(),
      dtNow.getUTCMonth(),
      dtNow.getUTCDate(),
      dtNow.getUTCHours(),
      dtNow.getUTCMinutes(),
      dtNow.getUTCSeconds(),
      dtNow.getUTCMilliseconds()
    );
    const dtY = utc.getFullYear();
    // Date months are 0-11
    const dtM = utc.getMonth() + 1;
    // For midnight:
    // 1: Set to UTC now
    const dtMidnight = new Date(utc.getTime());
    // 2: Set hours, minutes, seconds, milliseconds to 0 to obtain UTC midnight
    dtMidnight.setHours(0, 0, 0, 0);
    // 1 hour is 3.6e6 milliseconds.
    // Milliseconds / 3.6e6 = equivalent hours.
    // Equivalent hours / 24 = fractional day.
    // Formula is ms/3.6e6/24. Slightly more efficient: ms/(3.6e6*24=86400000)
    const fracDay = (utc.getTime() - dtMidnight.getTime()) / 86400000;
    dtT = utc.getDate() + fracDay;
    

    基准测试表明,这种方法可以达到 0.2 毫秒(接近 Luxon 的最大值),平均只有 0.008 毫秒。它比 Luxon 快 90-95%。

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2018-05-01
      • 2013-06-24
      • 1970-01-01
      • 2019-08-16
      相关资源
      最近更新 更多