构建cookie过期日期字符串时的性能问题(c ++)

时间:2012-08-22 12:25:44

标签: c++ performance cookies string-formatting

我有一个c ++代码,它为cookie构建一个到期日期字符串(类似于:"Thu, 31-Dec-2037 22:00:00 GMT")我需要它来自“now”。这是我的代码:

    ptime toDay(second_clock::universal_time());
    toDay += days(90);
    date d = toDay.date();
    string dayOfWeek = d.day_of_week().as_short_string();
    int dayOfMonth = d.day();
    string month = d.month().as_short_string();
    int year = (int)toDay.date().year();

    stringstream strs;
    strs << dayOfWeek << ", " << std::setfill('0') << std::setw(2) << dayOfMonth << "-" << month << "-" << year << " " << toDay.time_of_day() << " GMT";

    string defaultExpiration = strs.str();

此代码的性能非常糟糕,我猜这是stringstream使用 如果你们中的任何人有更快的选择,我会很乐意测试它 谢谢!

2 个答案:

答案 0 :(得分:1)

由于您正在使用boost,我认为您应该尝试使用其date_time输入/输出系统。它的作用是自动格式化您指定的布局中的日期和时间。 Here你可以看到关于它的增强教程。

基本上,你需要以你想要的格式为时间输出设置一个提升方面 - 有很多format specifiers,我相信你会弄明白。

我不确定这会带来性能提升,但我相信值得一试。毕竟,这就是子系统的目的 - 输出日期和时间。

答案 1 :(得分:0)

使用FastFormat找到了一种更快捷的方法,现在它看起来像是:

ptime today(second_clock::universal_time());
today += days(90);
date d = today.date();
int dayOfMonth = d.day();
int hoursOfDay = today.time_of_day().hours();
int minutesOfDay = today.time_of_day().minutes();

//this function if from "FastFormat"
string defaultExpiration(StringFormatter::Format("{0}, {1}{2}-{3}-{4} {5}{6}:{7}{8}:00 GMT",
    d.day_of_week().as_short_string(),
    dayOfMonth < 10 ? "0" : "",
    dayOfMonth,
    d.month().as_short_string(),
    (int)d.year(),
    hoursOfDay < 10 ? "0" : "",
    hoursOfDay,
    minutesOfDay < 10 ? "0" : "",
    minutesOfDay
    ));