Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Need help!!! some problems in c++
Index -> Programming, C++ -> C++ Help
Goto page 1, 2, 3  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
cqhqm150




PostPosted: Thu Oct 16, 2008 3:57 pm   Post subject: Need help!!! some problems in c++

when we want to assign a value to a specific position of a vector, there are two ways:
myvector.at(i) = 10 and myvector[i] = 10.

I just do not know which one is faster and why it is faster. (I think that the second one is faster, but I just cannot figure out the reason)

another problem: I use makefile to compile my program, but it can only compile my program without creating any a.out file, so I can not execute my program after compilation. Here is my makefile:
code:

CXX = g++
CXXFLAGS = -g -Wall
OBJECTS = file.o filedriver.o
EXEC = complexnumber

${EXEC} : $(OBJECTS)
        ${CXX} ${CXXFLAGS} $(OBJECTS) -o $@

file.o : file.h
filedriver.o : file.h

clean:
        rm -f $(OBJECTS) $(EXEC)


[edit by md]Fixed makefile block
Sponsor
Sponsor
Sponsor
sponsor
md




PostPosted: Thu Oct 16, 2008 5:09 pm   Post subject: RE:Need help!!! some problems in c++

Both C++ methods should be nearly as fast, though theoretically the first is slow since it returns a reference which is then assigned. The difference in instruction count is rather small.

The problem with your makefile is that you have nothing to build the object files, no dependencies on the source files.
S_Grimm




PostPosted: Thu Oct 16, 2008 5:26 pm   Post subject: RE:Need help!!! some problems in c++

please do not post "I need help titles." Also md is right. your compiler needs source files to comile. yours has none. its like parachuting without a chute.
cqhqm150




PostPosted: Thu Oct 16, 2008 6:21 pm   Post subject: RE:Need help!!! some problems in c++

thank you. I will not post "need help" next time.
cqhqm150




PostPosted: Thu Oct 16, 2008 6:39 pm   Post subject: RE:Need help!!! some problems in c++

I solved my makefile problem. Because the executable file is complexnumber instead of a.out, makefile create a file named complexnumber. That's why I can not find a.out after compilation.
wtd




PostPosted: Thu Oct 16, 2008 7:57 pm   Post subject: RE:Need help!!! some problems in c++

That may have made it appear to work, but you need to actually compile some source files. The file.o and filedriver.o rules do not require that the source (presumably *.cpp) even be present, and they certainly don't perform any sort of compilation.
btiffin




PostPosted: Fri Oct 17, 2008 1:13 am   Post subject: RE:Need help!!! some problems in c++

Old guy ramble;

Re the vector method or indexing overload; try running some tiny source that includes the two different through
code:
g++ -S
and you'll see that md's assertion of the instruction counts being very close.

Re make (for everyone); don't forget that make usually ships with a huge ugly bag of built-in rules. For instance
code:
$ make program

will look in the dir (with no Makefile whatsoever) for program.c and actually add -o program to the cc command it uses by default. If no program.c, and make finds program.cpp, c++ will be used for the compile. I have no clue about the actual rule chain for default make ... but I know .c trumps .cpp

cqhqm150's make commands would behave just as he implied. Overrides in the Makefile will change cxx to g++ etc, but it is mostly the default rules that get the build done in this case. make simply tries all its rules on complexnumber. As wtd points out, the built-in rule chain makes it appear to work and by fluke the build actually does work for this simple case, with all the potential problems lying in wait. Wink

cqhqm150; This may be poor advice; but I usually write a script that includes all the tectonics for a build while first developing anything. Explicitly state the build commands and comment in where any special external libraries come from. When tectonic works, then I move to the efficiency of a Makefile and make.

Cheers
Rigby5




PostPosted: Mon Oct 20, 2008 9:03 pm   Post subject: RE:Need help!!! some problems in c++

myvector.at(i) = 10;

Is much slower then

myvector[i] = 10;

The size of the program has nothing to do with it.
The difference is that the first calls a function, while the second is done entirely in line by the code generated by the compiler, that calculated the address ahead of time.
These days the difference is trivial, but in the old days you some times needed to avoid excess function calls due to the need to push and pop all the registers.
Sponsor
Sponsor
Sponsor
sponsor
md




PostPosted: Mon Oct 20, 2008 11:12 pm   Post subject: Re: RE:Need help!!! some problems in c++

Rigby5 @ 2008-10-20, 9:03 pm wrote:
myvector.at(i) = 10;

Is much slower then

myvector[i] = 10;

The size of the program has nothing to do with it.
The difference is that the first calls a function, while the second is done entirely in line by the code generated by the compiler, that calculated the address ahead of time.
These days the difference is trivial, but in the old days you some times needed to avoid excess function calls due to the need to push and pop all the registers.


Don't be so sure. std::vector<T>::at() could very easily be an inline function just like std::vector<T>::operator[](). The only real difference between the two methods is actually in the C++ course. Both in fact generate remarkably similar assembly, especially since the address cannot be calculated in advance for a std::vector (with the possible exception of a static std::vector which is very uncommon).

For example, in this very quick (and fast) implementation both are *exactly* the same
c++:

template<class T>
class foo
{
private:
        T *array;
        T temp;
        int max;

public:
        foo(int max)
        {
                array = new T[max];
                this->max = max;
        }
       
        inline T& operator[](int index)
        {
                if( 0 < index && index < max)
                        return array[index];
                else
                        return temp;
        }

        inline T& at(int index)
        {
                if( 0 < index && index < max)
                        return array[index];
                else
                        return temp;
        }

};

int main(int argc, char **argv)
{
        foo<int> bar(10);
       
        bar[1] = 10;
        bar.at(2) = 10;

        return 0;
}
DemonWasp




PostPosted: Tue Oct 21, 2008 11:47 pm   Post subject: RE:Need help!!! some problems in c++

I just dealt with this exact issue on an assignment for one of my own CS courses (CS246 at UW, incidentally). Here's some test results (all times in seconds, all executed on the same machine, all compiled with the same compiler):

Vector, checked access, no optimisation: 2.380
Vector, checked access, -O2 optimisation: 0.152
Vector, unchecked access, no optimisation: 1.028
Vector, unchecked access, -O2 optimisation: 0.120

This is with "checked access" meaning using .at(), which checks bounds, and "unchecked" meaning using the access operator, which does not.

That's the key difference here: if you use the std::vector<T>::at(), it will check that the requested index is not out-of-bounds, whereas using std::vector<T>::operator[]() will not.
Pockets




PostPosted: Thu Oct 23, 2008 11:13 am   Post subject: RE:Need help!!! some problems in c++

Spot on there, DemonWasp. Checked access is great for reducing the likelihood someone can overflow your program (but it's always a possibility). Unchecked access is the old standard, built for speed above all else. Unchecked is fine for things like school programs (unless the assignment includes making it secure), but the function call is there for a good reason.

Funny thing about things built for speed. Some guys a while back thought it'd be faster to drop the first two digits of the year date...
btiffin




PostPosted: Fri Oct 24, 2008 1:00 am   Post subject: Re: RE:Need help!!! some problems in c++

Pockets @ Thu Oct 23, 2008 11:13 am wrote:

Funny thing about things built for speed. Some guys a while back thought it'd be faster to drop the first two digits of the year date...


Re dates; Not quite.

In 1960, hard disk cost many many thousands of dollars per meg. Many many. Some $100,000 for a 25 meg disc.

So, if a bank could save 2 bytes off each of 1 million transactions, well that was like saving $10,000 (1960's dollars). Huge. Paid the programmer for his year. The culture stuck with the industry right up till the late 90's.

Very few old timer programmers would truncate a date for speed, not from a CPU perspective anyway. Bus speed to storage would be a larger concern. Data space was the primary reason the COBOLers of old got away with this.

Old guy portents of doom and a ranting follows
Anyone in highschool now will be just hitting their mid 40's when the Unix 32 bit date epoch rolls over and really could take some systems for a loop or two. Y2K was a visible problem. The 32bit Epoch problem less visible, more insidious. People may seem "smarter" now, but the 1970 based datetime routines are embedded in a LOT of systems. The esteemed members of compsci.ca will be in for an employment boom as the world bitches about "those foolish and crotchety old out of date C programmers" that are causing everyone grief.

03:14:07 AM January 19, 2038 ... any existent 32bit clib based system will think it is 00:00:00 January 01, 1970.

And anyone reading this thinking ... oh, all that software will be replaced by then, I'll ask; Do you think that code you write now is so shitty that it won't last 30 years? 30 years in not a long time. Look at the years of service expected from aircraft or power plants.

From personal experience ... I still get called in to support a 25 year old system that I was in on the initial development of.

And so you know that I've eaten my own dog food ... we built an index that included a Priority Category Realtime Outage key smudged into an 6 byte field. Someone wanted it separated by In Service, Out of Service. So we stole a bit from the 32bit datetime field. That index will become unusable somewhen in 2015. The system won't fail in any critical sense. It's a Forth system that compiles from source every morning after the back up. There is an assert to cause the load to fail on the magic day. So somewhen in 2015 I'll probably get a call that the system didn't load, and the quick fix will be to remove the assertion and let the index sort wrong. This is not a hidden fact of the system ... it was and is well documented and we got approval from management.

And on a personal note; Sorry Pockets ... I'm not trying to pick on you ... It's an old fart ranting to everyone to be careful that when you ignore history, you are bound to repeat its mistakes. Y2K didn't really teach anyone anything as far as I can tell. But it sure scared the bejeezus out of people in positions of fiduciary responsibility. So after the world made it through the year 2000 mythical meltdown, the big boys looked at IT, mad having been forced to spend millions on systems that they had already spent millions on for no benefit other than "just in case", and yanked all our play money away ... sealing the fate of the dot com bust.

And more ranting ... COBOL and string held dates are rarely in control of large electro-magnet power generating systems. Unix epoch 32 bit C datetimes ... hmm. Let these AC systems drift out of phase ... leading to voltage drop, without compensation with either a change to resistance and/or current and you get a boat load of heat ... boat loads. Y2K may end up looking like a cake walk.

Cheers,
and sorry if I went too far off topic for the thread
Edit; typos
Rigby5




PostPosted: Fri Oct 24, 2008 2:22 pm   Post subject: RE:Need help!!! some problems in c++

Md, good point with the inline function.
However, I think the compiler can do even better at array indexing when not constrained by the code of an inline function.
md




PostPosted: Fri Oct 24, 2008 11:01 pm   Post subject: Re: RE:Need help!!! some problems in c++

Rigby5 @ 2008-10-24, 2:22 pm wrote:
Md, good point with the inline function.
However, I think the compiler can do even better at array indexing when not constrained by the code of an inline function.


The underlying memory layout of a vector may not be an array. It most likely is... but there are alternate and equally fast methods for creating vectors that are a bit more complex.

In either case the compiler is far from constrained when you tell it to optimize anyways. It will inline functions, re-arrange code, even get rid of things you wrote if it can do the same thing faster. Compilers are very good at optimization, and without too much owrk on the programmers part they will work very well.

Code optimization is a assembly skill, not really a C++ skill.
OneOffDriveByPoster




PostPosted: Sun Oct 26, 2008 3:10 pm   Post subject: Re: RE:Need help!!! some problems in c++

md @ Fri Oct 24, 2008 11:01 pm wrote:
The underlying memory layout of a vector may not be an array. It most likely is... but there are alternate and equally fast methods for creating vectors that are a bit more complex.
I'm interested in knowing what these ways are.
In C++, you are limited by the following:
Quote:
The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 3  [ 31 Posts ]
Goto page 1, 2, 3  Next
Jump to:   


Style:  
Search: