|
-
July 1st, 2004, 06:01 AM
#1
Problem with stringstream and multithreading
SSTREAM has a patch to vastly improve performance
http://www.dinkumware.com/vc_fixes.html
I've compiled the following test as a console app:
Code:
#include <sstream>
#include <fstream>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
ofstream out("out.txt");
stringstream ss;
clock_t start,= clock();;
for (int i=0; i<100000; ++i)
ss << "," << i;
ss << endl;
clock_t finish = clock();
cout << finish-start << endl;
out << ss.str();
return 0;
}
With the patch, it takes 1000 ticks on my computer to execute (debug mode). Using the original SSTREAM it takes 37500 ticks (about 40 times longer).
However, using the patched SSTREAM file and setting the compiler option to /MDd (multi thread), rather than the default /MLd (single thread) takes execution time back upto 37500 ticks again.
Why is this happening, and how can I get the multithreaded version to work properly? (I want to do a similar thing in an multi threaded MFC application).
Thanks
-
July 1st, 2004, 06:26 AM
#2
Changing the settings to :
"Use MFC in a Static Library" seems to help.
-
July 1st, 2004, 06:38 AM
#3
And multithreading does inroduces its own overhead, so that should not surprise one. The stream functions have to be synchronised and some of the kernel mode synchronisations functions eat up a lot of cycles.
Say no to supplying ready made code for homework/work assignments!!
Please rate this post!
-
July 1st, 2004, 07:03 AM
#4
Sure enough, using statically linked MFC does solve the problem. Thanks Philip. But:
1) how to convert my existing dynamically linked project to static?
2) I don't really want to have MFC statically linked. Do you think a compiler upgrade (vc6 sp5 currently) will solve the problem, without introducing hundreds more?
3) any other options?
Thank you
-
July 1st, 2004, 07:33 AM
#5
One possibility is to write directly to a string via a a large
number of calls to stringstream, but reserving a large
enough amount in the string so re-allocation/copying
does not need to occur. Here is an example :
1) add the following templated function ...
Code:
template <typename T>
std::string ToString(const T & val)
{
std::stringstream ss;
ss << val;
return ss.str();
}
2) create the string as follows. You need to estimate the
size of the string before hand. In the xample below, I used
10 times the number of elements being "written"
Code:
std::string str;
int N = 100000;
str.reserve(N*10);
for (int i=0; i<N; ++i)
{
str += "," + ToString(i);
}
-
July 1st, 2004, 08:11 AM
#6
Thanks, that is a reasonable work around
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|