Hi, is there any way I can erase the contents of the console?
Thanks,
Printable View
Hi, is there any way I can erase the contents of the console?
Thanks,
Code:for ( int i = 0; i < 50; ++i ) {
putchar('\n');
}
Acutally IMHO thats not a very good way to clear the console. For one, it moves the cursor to the bottom, and for two you dont know the size of the console window.
Check out http://faq.cprogramming.com
This has been asked a BAziiilliiioooon times, search the faq and the boards you will find many ways, many arguments, many fights, and many other things about clearing the screen.
Thanks
It's covered, along with a load of other stuff, in part 2 of my console programming tutorial.
For speed purposes, do the following:Quote:
Originally Posted by Antigloss
for (register int i = 0; i < 50; ++i ) {
putchar('\n');
}
The loop control variable is saved as a register in the computer instead of memory, so accessing it will be much more efficient. For today's computers, it's probably not going to be a difference, but you don't know what computer your users will have. Regardless, it's still theoretically faster accessing a register than accessing memory.
Rare is the compiler that's not smart enough to put a loop variable into a register. In fact, a loop with fixed run length will be either unrolled (though 50 iterations might be too many for that), or implemented using the x86 LOOP instruction, which requires the counter to be in the ECX register.
Most modern compilers are, in most situations, better off deciding for themselves which variables go into registers.
Stupid compilers... they think they're so smart...
Microsoft 32-bit compilers ignore the register keyword. I suppose other compiler do too.
Eitehr way, I think it's a good habit to get into, because there's so many systems out in the world that depend on C/C++ code.
According to Microsoft:
The compiler does not honor user requests for register variables; instead, it makes its own register choices when global optimizations are on.
I still disagree. The register keyword makes a low-level optimization choice that you shouldn't make until profiling actually shows that there's significant time lost.
> Eitehr way, I think it's a good habit to get into
ROFLMAO - I seriously doubt you'll find a serious compiler which can't do this.
If you do, you've got other problems to think about.
Such twee micro-optimisations are really a waste of effort nowadays. For a start, you have no idea how many registers are on the current machine (yes, I'm talking about the real world, not the insulated world of wintel).
Besides, you fail to take into account the work inside the loop (lots - I/O is expensive) with the work of the loop itself (almost nothing).
Consider the possibility that the compiler decides to follow your guess as opposed to what it knows is the real register usage, and as a result generates WORSE code than what it would have generated had you not said anything.
... that's another way to say it ...
Does anyone know where I can download curses.h?
Well, you can get ncurses here:
http://www.gnu.org/software/ncurses/ncurses.html
It's UNIX-only, though.
Public Domain Curses looks more promising for Windows:
http://sourceforge.net/projects/pdcurses
I still think it's a good habit to get into. In fact, I know it is. C++ is all about systems programming, so eventually you'll get into compiler design, interpreters, device drivers, operating systems, editors, file utilities, and performance executives that will need the register keyword. Think outside of MS's compilers. There's a whole different world out there where you shouldn't second-guess each compiler (and there's tons of older ones you'll need to use eventually). If it ignores the register keyword, big deal. At least you sent a request, and that's better than not doing so. That's why it's a good habit to get into - it's good practice, and it shows that you care about a possible performance boost, or some special treatment from the compiler.
This is Microsoft specific if you have Visual C++:
The compiler does not accept user requests for register variables; instead, it makes its own register choices when global register-allocation optimization (/Oe option) is on. However, all other semantics associated with the register keyword are honored.
Honestly I think thats kinda bogus dxfoo, hate to say it, but the register part of the for loop is a trivial optimization at best.
C++ is NOT just about systems programming... I see it more as a fast, very flexible programming language. It has its root in systems programming for sure, but there are many things which take an even higher level language. Just for a note, I am a systems programmer, and generally we use it in everyday apps more than we use for basic systems programming.
But in any event, back to the thread at hand, the cprogramming faq has a lot of good things in it, I would suggest searching it, then asking for help, it can help save your time as well :)
"However, all other semantics associated with the register keyword are honored." - RTFM.
Register would work in this for-loop situation, because by default, Microsoft IDE's leaves the /Od and /Oe option unchecked.
If you want Microsoft to allow this optimization, for example with VC++ 2005, go to project-> Properties -> Configuration -> C/C++ -> Optimization -> Optimization setting = "Full Optimization".
The default option is "DISABLED (/0d)." Even /0e is disabled. (RTFM again or look at MS's quote above in my other post in how it relates to /0e).
I give information. You can either listen, look into it more, or waste time arguing.
Says who? Yes, C++ has a strong foundation in systems programming, but it's also popular with applications programmers that don't give one whit about the register keyword, and shouldn't. I think your priorities are seriously misplaced. If you find yourself on a compiler that honors your hint and it actually improves performance, you probably need to do some higher level optimizations before trying to micromanage everything. Use better algorithms first, then look to the smaller stuff. I mean really, if you need control over your registers, why aren't you using assembly?Quote:
C++ is all about systems programming, so eventually you'll get into compiler design, interpreters, device drivers, operating systems, editors, file utilities, and performance executives that will need the register keyword.
You offer information, I offer experience. Unless your title is a lie, you could benefit from it. ;)Quote:
I give information. You can either listen, look into it more, or waste time arguing.
I just gave you hard proof that register is necessary because /0e is not enabled by default. Microsoft quotes, for the 3rd time, "...instead, it makes its own register choices when global register-allocation optimization (/Oe option) is on." Why is there an arguement when this is coming directly from the manual?
Lol because its not necessary. Would you stick a band-aid on your thumb before you might cut yourself? It shouldn't be in the realm of this conversation because it has no bearing on clearing a console. Optimization comes last, after bugs/fixes have been worked out. Small optimizations like this are low priority, and generally unnecessary. More importantly as narf said, algorithms come first, then simple things such as register(if even needed). Anyway, this is silly to argue about... use register if you want, but pay attention to the more important things first.
You guys assumed register was ignored by the compiler, and I personally found you guys ignorant when I even proved this wrong. Evn five posts later! Yes, it was necessary to explain because you guys do not understand Microsoft's compiler when it comes to the register keyword. Now that it's explained, you guys are slowing down the program without registers as loop-control variables. Follow my directions, and the register keyword will only help optimize your pogram. I'm referring to his for-loop. If he uses register, it will give him a better performance boost. That's all I was pointing to lol. :)
Listen, next time you want to argue that applying register won't have any effect, RTFM! Why can't you apply what I quoted? It should have ended this needless conversation an hour ago.
Oh, please, dxfoo, stop preaching! You're just making yourself look ridiculous.
Give me one good reason why I would not enable global optimizations for my release build.
I'm not arguing that register might have an effect. I'm telling you that you're focusing on the wrong things for optimization. But if you really want to keep talking about register, I refuse to listen until you have the "hard proof" from a profiler showing that not only is there an improvement in speed, but that there's a significant improvement that warrants using register without even considering that a far better improvement could be had by using better algorithms.Quote:
Why is there an arguement when this is coming directly from the manual?
See the difference? You're talking from theory--probably from one of your classes--and I'm talking from practical experience in the real world. Please don't take offense. I'm just trying to give you another perspective.
You'd be wise to avoid absolutes. Not only could register not give him better performance, it could be slower. It's been repeatedly proven that the compiler is way smarter than the programmer when it comes to placing variables in registers. Yet people still try to pretend that they can magically find performance optimizations just by looking at tiny snippets of code. In practice, it's generally better to err on the side of simplicity, then optimize when you can prove that there's a speed problem.Quote:
If he uses register, it will give him a better performance boost.
Feel free to be offended at my next statement, but if you have any personal attacks, direct them to my private messages.Quote:
I hope you guys start listening more. You might learn something.
You should spend more time listening and less time trying to defend your position. If you're too busy talking, you miss the valid points that are being made, and you remain ignorant.
Of course here is a very simple way to clear up this silly argument -- have the compiler produce an assembly listing of the program with and without use of register keyword. In the test I made with VC++ 6.0 release build it made no difference, both programs produced the exact assembly program. I even tried adding other stuff in the function to see what affect additional integers had -- none. The compiler still used a register for loop counters whether I used register keyword or not.
Of course other compilers may nor may not have the same affect.
For speed purposes, do the following:Quote:
Eitehr way, I think it's a good habit to get into, because there's so many systems out in the world that depend on C/C++ code.
Understand the difference between writing a simple program on your PC to help you learn C++, and writing a program intended to be run on a microcontroller.
I tested with VC7. The register keyword made no difference, either with optimisation turned on or off.
Unoptimized assembly:
Optimized (/02) assembly:Code:; 5 : register int i;
; 6 :
; 7 : for (i = 0; i < 50; i++)
mov DWORD PTR _i$[ebp], 0
jmp SHORT $L794
$L795:
mov eax, DWORD PTR _i$[ebp]
add eax, 1
mov DWORD PTR _i$[ebp], eax
$L794:
cmp DWORD PTR _i$[ebp], 50 ; 00000032H
jge SHORT $L792
Code:; 5 : int i;
; 6 :
; 7 : for (i = 0; i < 50; i++)
mov esi, 50 ; 00000032H
$L864:
// Loop contents omitted.
; 5 : int i;
; 6 :
; 7 : for (i = 0; i < 50; i++)
dec esi
jne SHORT $L864
> Think outside of MS's compilers.
I've seen no evidence that you have.
> where you shouldn't second-guess each compiler
So why insist on pointless micro-optimisations like using 'register', which a lot of optimisers simply ignore nowadays.
> it's good practice, and it shows that you care about a possible performance boost
No, choosing good algorithms counts. No amount of 'register' will save your bubble sort from being pounded into the ground by any half-decent quicksort. You're focussing on the wrong issue.
> Microsoft quotes, for the 3rd time, ".
Once again, you're trying to extrapolate the universe from one specific implementation. I don't give a rats ass what YOUR compiler says about register, this board caters for all compilers / operating systems, so stop preaching what "my" compiler does as being the best advice for everyone else.
He'll learn when the real world bites him. After all, as a CS student he's bullet proof. Us old hacks that have actually been doing the job for real money in the real world for years know nothing.
Where's that damned rep button when you need it.
Hey I am a CS student and I listen to my elders ;)
Me, too, and I also know these kinds of things already ;)
I still am cooler than you so ya.
Sad thing is this thread was about clearing the screen and turned into this.
Considering the original question is answered in the FAQ, I see no loss. Plus, the entertainment value of this thread is priceless. Nothing like watching a CS student give a lecture to people who have been programming for 10-20 years.Quote:
Sad thing is this thread was about clearing the screen and turned into this.
Lets see loop costs a memory write that would cached at the very least, this is a pretty quick operation. Body of loop costs a device output, even with buffering this is a pretty slow operation.
Now instead of pretty little worthless optimizations why not using a better algo to begin with? Heck this would be faster and give the exact same result:
Where ... is 46 more \nCode:puts("\n\n...\n\n");
I am very new to C++, but uhh…what is wrong with telling the poor guy to just use the following instead of doing it himself?:
For Visual C++, just make sure to #include <iostream>Code:system("cls");
I think that is iostream.h in Borland c++? Or maybe that is just old versions. Like I said, I am new.
<cstdlib>, or <stdlib.h> for old compilers. But I'm sure a few people here will be happy to tell you that system() is slow, and unsafe, and not portable. In my opinion, it's all good as long as you know the costs and they're acceptable.Quote:
just make sure to #include <iostream>
Uhh nope, I do not. Nor was I aware of any of the issues you mentioned!Quote:
In my opinion, it's all good as long as you know the costs and they're acceptable.
system() is completly portable -- it is part of the standard C libraries, so all C compliant compilers regardless of platform support it. embedded c compilers are not fully c compliant, so they are not bound by those standards.
There is no completly portable way of spawning one program from another. All the functions (such as system, spawnl, pipes, sockets, CreateProcess, WinExec, and sevefal others) require intimate knowledge of the operating system. So -- using system() is no more and no less portable than using any other of the several functions.
system() itself is portable, but system("cls"); is not. Thats what people here tend to mean when we say its a non portable solution.
I'm a CS student too, and here's what I know from knowledge gained in my algorithms course (using "A Practical Introduction to Data Structures and Algorithm Analysis" by Shaffer) + common senseQuote:
Originally Posted by adrianxw
(note: not preaching at anybody, but who knows, this might actually come in handy to someone who doesn't already know it)
running the loop fifty times results in the following happening:
i is assigned the value 0, 1 time.
i is incremented (has 1 added) 50 times.
i is checked against the vlue '50' 51 times.
putchar('\n') is called 50 times.
i.e. At this point it should be obvious to mostly anyone who's spent any time programming that putchar is taking more time than any operations on i are taking, even if you take into account the fact that it's buffered output.
To go a little further, here is approximately what is happening(while calling putchar), from my knowledge of C:
first the character '\n' gets copied (I'm not 100% sure of this part, but like 95% sure) and sent to the function putchar. putchar then sends this copied character to the output buffer - which may even require another (lower level) function being run. All in all, putchar('\n) is *at least* 10 times as long as the time required to assign 0 to i (actualy a whole lot more, I am willing to bet money). incrementing i will take even less time than initializing i.
Now, the proposed optimization is to change i so that access to it will be faster, but consider what's happening first:
i is taking a certain period of time to be initialized, and to be incremented 50 times, and to be checked against 50, 51 times. putchar is taking (from earlier argument) about 10 times as long as the increment, and let's say that an increment on i takes an average of 1/2 as long as the initialization of i. a check against 50 probably takes somewhere around as long as initializing i (although you could optimize that with a good algorithm)
now, i is taking 1 time unit to be initialized, and 25 units (50/2) to be incremented throughout the course of the loop, and around 51 units to be checked.
All together, i is taking around 77 units of time throughout the course of the loop.
putchar, on the other hand, takes at least 10 units of time per run, and running 50 times, which means it is taking *500* units of time (probably lot more, since it probably takes a lot more than 10 times as long as an operation on i, but let's keep to the times I already mentioned).
now, let's say that setting i up as a register variable will cut all access times on i by 20%; so now instead of taking 77 time units it only takes 61.6 time units. Let's see how much time we saved on our total operation:
total time without register: 577
total time with register: 561.6
total difference: about 2.7%
so, assuming putchar takes only 10 times as long as an operation on i, we saved 3% of the time. However, what if putchar takes 50 times as long as an operation on i? well, then:
total time without register: 2577
total time with register: 2561.6
total difference: about 0.6%
The main point is that operations on the loop variable are *already* a very small part of the overall loop. changing it to a register int doesn't make much difference; but, as you can see, the place where the difference *is* made is *INSIDE* the loop [putchar] :)
If you read my tutorial, which I linked to above, you'll note I do not advocate the use of any kind of loop to clear the screen.....Quote:
as you can see, the place where the difference *is* made is *INSIDE* the loop
Just to add to what Cobras said, there's another detail to putting i into a register that was conveniently forgotten. Let's stay with the IA32 arch for the moment, with its 8 general purpose registers. Now, a loop counter will most commonly be stored in the ecx registers. The fun part is that, with most compilers, ecx is not preserved across function calls. In other words, somewhere inside putchar(), another value might be assigned to it. (E.g. the loop counter/pointer in a memcpy call if the buffer is flushed.)
Since putchar() is a library function, the compiler cannot even do global optimizations. So i cannot be put into a register in the first place - or even if it is in a preserved register, the called function would still have to store it on the stack - in memory.
system("put anything at all here") is not portable. And the point is ....? If you're writing portable code then you wouldn't use system() function for anything. If you want to use it then put it in preprocessor directives like this. But of course I don't do this because I could care less about the portability of my text/example programs. And if I'm writing a program for MS-Windows os and use other win32 api functions portability of the code isn't even an issue, so again system("cls") is a good way to clear the screen.Quote:
Originally Posted by Thantos
Code:#if defined(_WIN32)
system("cls");
#elif defined(_UNIX)
system("clear");
#elif defined(_MAC)
system("put something else here");
#endif
system("cls") is not the best and safest way to clear the screen by any means. Using the bottom of this page would probably be one of the better ways.
The left side of the quotation. The entire issue is about portability.Quote:
system("put anything at all here") is not portable. And the point is ....?
Similar to that, but not exactly like that. Otherwise you'd end up in preprocessor hell. How about defining a portable interface, then just changing the code behind the interface when you port the code:Quote:
If you want to use it then put it in preprocessor directives like this.
You call clear_screen() however many umpteen times you need to, but portability isn't affected because to go to Linux you only need to change one thing in one place, "CLS" to "clear" in the definition of clear_screen(). A lot of people seem to think portable code means you can compile everywhere without change. That's the ideal, sure. But almost any non-trivial program has to use non-portable stuff, so portability really means how easy it is to get code to compile somewhere else. A portable program fixes the deck so that there's only one point of change for any given non-portable feature.Code:void clear_screen() {
system("CLS");
}
You can get the ideal by hacking each port into the program with the preprocessor, but that gets ugly and unwieldy very fast. I don't consider it ideal after two branches, even if you do it intelligently to avoid littering the code with preprocessor directives. If you can reach the ideal in a clean way, great! If not--like with clearing the screen--fix the deck for portability and go have a pint. :)
Yes I know all those preprocessor directives get pretty ugly very quickly. And it make it difficult to port the program to a new platform.Quote:
Originally Posted by Narf
This is exactly why programming discussion boards are so great today! :) You get a lot of different ideas from other programmers, making the end result a lot better for everybody. Using your idea we could put all os-dependent code in a library then link the program to whatever os lib we want.
Everybody seems to have their own method to clear the screen. They post their methods and get shot down. The people who shot down the other methods have their own methods shot down. Is there any function that everybody agrees is the best? I guess thats a dumb question but is there any way to do it that alot of people think is at least good? And can anybody that has curses.h in their library post it?
Thanks,
There is no best way. You just have to do what works best for you.
Ok, but what is the most commonly used method?
Out growing the need to clear the console at all.Quote:
Originally Posted by beanroaster
If you're using a windows computer, I'd probably go with the WINDOWS CONSOLE OPTION listed in the FAQ.
http://faq.cprogramming.com/cgi-bin/...&id=1043284385
Or check Adrianxw's tutorial, there's probably one in there.
What is Adrianxw's tutorial? And how do I kill this thread?
Look at his first post in the thread - it's like 5 down from the top.Quote:
What is Adrianxw's tutorial?
You don't. You get a mod to do it. And I agree - it should be dead. If anyone wants it reopened PM me or another mod.Quote:
And how do I kill this thread?