I have the following 'interface' to the C++ std::list
and I was wondering how I could make it go faster. In particular, it needs to be able to evaluate up to two million operations in a matter of a couple seconds. Right now it's at around 8 seconds.
#include <iostream>
#include <list>
int main()
{
int n, m;
std::cin >> n >> m;
std::list<int> myList (n);
for (int i = 0 ; i < m; i++) {
std::string op;
std::cin >> op;
if (op[1] == 'O') {
std::cout << myList.back() << '\n';
myList.pop_back();
} else {
int val;
std::cin >> val;
myList.push_back(val);
}
}
return 0;
}
It reads input in the form
3 4
PUSH 2
PUSH 3
POP
POP
With expected output
3
2
Where 3 corresponds to highest value, and 4 corresponds to number of operations.
The operations are guaranteed to be safe (no POPing empty stacks), and each value is used at most once (this part in particular I feel I could optimize, but I'm not sure how).
Right now I'm testing with the following Python script:
print "1000000 2000000"
for val in xrange(1,1000001):
print "PUSH ", val
for _ in xrange(0,1000000):
print "POP"
And getting this for time:
8.89 real 0.00 user 0.01 sys
I started out using std::stack
, but tried switching to std::list
in order to give a preset size, so as to not need to reallocate memory. This did not help the time any, but that's where it stands as of now.
std::vector
increaseduser
andsys
, andreal
remained about the same.8.76 real 7.29 user 1.44 sys
\$\endgroup\$PUSH 1\nPUSH 2\n...PUSH 1000000\nPOP\nPOP...POP
\$\endgroup\$0.00 user
in your question is not really believable, are you sure that your test or copy/paste was accurate (and repeatable)? Also make sure you're timing only the C++ part, not the python generator (store the output of the generator in a file, and time only the C++ part). \$\endgroup\$