Let's say there's a section of code which takes a big chunk of the overall program time (~20%), which consists on converting from a given type (among options: string, char, short, int, float, unsigneds, ...) to string. The easy way to do this would be something like:

template<class T>
string toString(T sAttrvalue) {
    stringstream ss;
    ss << T;

    string res=ss.str();

    if(res=="x" || res=="y")
        return "k";

    return res;
}

But the performance is too poor (even if it improves by using a static stringstream and doing ss.str("") in the beginning of the function).

Any other ideas on how to make it go faster? (what would you think of using another function argument which specifies the time and, from there, use sprintf?)

有帮助吗?

解决方案

You could try using template specialization in addition to the code you gave, to optimize the most common cases (this is how, for example, vector<bool> can be more space-efficient).

For example:

template<>
string toString<char>(char sAttrValue) {
    ...
}

template<>
string toString<int>(int sAttrValue) {
    ...
}

And so on for the other types, each one using a conversion method specific and optimized for that type. Any type that doesn't match one of these specialized templates will fall back to the default stringstream method.

其他提示

A few points:

  • to measure accurately, get time snapshot, call the function in a loop for X times (say X = 10000), then get time again (see clock()). Substract initial time from final time and divide by X.

    This will give you an accurate measurement.

  • ostringstream is not made for performance, it is made for uniform, extensible buffered output (buffered = slow).

    You should particularize the template by type and use faster alternatives. If possible, do not switch to sprintf, but use other alternatives (itoa, allocate string directly, etc).

    If you do use sprintf, be paranoid about it (check return value, corner cases, etc).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top