【问题标题】:Is there a better way to calculate a time period?有没有更好的方法来计算时间段?
【发布时间】:2011-06-26 21:59:25
【问题描述】:

我有以下代码。这是在 cellForRowAtIndexPath 中计算的,所以我认为它可能有点贵。有没有更好的方法来计算时间段?

+(NSString*)toShortTimeIntervalString:(NSString*)sDate  
{ 
    NSDateFormatter* df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
    [df release];

    NSDate* today = [[NSDate alloc] init];
    NSDate *d = date; //[_twitter_dateFormatter dateFromString:sDate];
    NSTimeInterval interval = [today timeIntervalSinceDate:d];
    [today release];

    //TODO: added ABS wrapper
    double res = 0;
    NSString* result;
    if(interval > SECONDS_IN_WEEK)
    {
        res = fabs(interval / SECONDS_IN_WEEK);
        result = [NSString stringWithFormat:@"%1.0fw ago", res];
    }
    else if(interval > SECONDS_IN_DAY)
    {
        res = fabs(interval / SECONDS_IN_DAY);
        result = [NSString stringWithFormat:@"%1.0fd ago", res];
    }
    else if (interval > SECONDS_IN_HOUR){
        res = fabs(interval / SECONDS_IN_HOUR);
        result = [NSString stringWithFormat:@"%1.0fh ago", res];
    }
    else if (interval > SECONDS_IN_MIN) {
        res = fabs(interval / SECONDS_IN_MIN);
        result = [NSString stringWithFormat:@"%1.0fm ago", res];
    }
    else
    {
        interval = fabs(interval);
        result = [NSString stringWithFormat:@"%1.0fs ago", interval];
    }
    return result;
}

【问题讨论】:

  • 这对我来说看起来不错,但我怀疑它太慢了。
  • 不要假设,要衡量。如果你测量它并且它太慢了,找出是什么造成了这种情况,然后询问如何改进它。如果您不知道如何衡量或如何分析,请询问。 “你觉得这太慢了吗?”这不是一个很好的问题。
  • 乔希,我测了一下,它占用了 62% 的时间

标签: iphone objective-c cocoa-touch performance nsdate


【解决方案1】:

这看起来并不算太糟糕,我怀疑你会从中看到太多的性能影响。为了提高效率,您可以考虑只创建一个 NSDataFormatter(将其保存在实例变量或static 变量中)并重用它。或者更好的是,如果您可以事先将所有内容都转换为 NSDates,那么您就不必每次都使用格式化程序。

但是,您真的在这里看到了任何性能问题吗?在尝试和优化之前,您应该使用 Instruments 来调查实际占用时间的原因。

【讨论】:

  • 时间分析器显示在单元创建期间有 62% 的时间花在该方法上。我应该使用不同的仪器进行测量吗?
  • 时间分析器是这里的正确工具。并且缓存格式化的日期绝对是正确的起点;初始化一个新的格式实际上是相当昂贵的。
【解决方案2】:

并非如此,但有一个 few categories 封装了该逻辑并使其成为您的单行电话。

【讨论】:

    【解决方案3】:

    最近我一直在执行复杂的计算(绘制一系列年份的图表),并且我在循环中使用 NSDate。使用时间分析器 NSDate、NSDateFormater 分析后,NSCalendar 是根本原因。我改用 C 类型(time_t + timeinfo),它大大提高了速度。

    虽然它们速度更快,但功能更少,如果你需要处理 TimeZone 等,NSDate 可能更容易处理。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多