Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Why is everyone so adamant on coding in C?

Status
Not open for further replies.

Jon Wilder

Active Member
It seems that hardly anyone codes in primarily assembly anymore, yet I've read pretty much everywhere that assembly code seems to be much more efficient than C.

Besides saving on lines of code and typing time, what advantages does C have over assembly? If assembly is much more efficient than C then why would C be considered a "higher level language"?
 
As for why it's a higher level language it's because its level of abstraction is higher.
High-level programming language - Wikipedia, the free encyclopedia

People use it because it's easier to program in. It's easier to port code to other microcontrollers or even take code from libraries used on older PC's. Assembly is still preferred in areas where the programming has to be very efficient, but it's not portable. I work with 3 different microcontroller architectures at the moment and I have code that I can share between them without much trouble. For instance, I wanted to use a touch screen controller and I took code from a Linux driver to use it. Any inefficiency in programming in a higher level language is easily eaten up by faster microcontrollers with more FLASH/RAM now.
 
It seems that hardly anyone codes in primarily assembly anymore, yet I've read pretty much everywhere that assembly code seems to be much more efficient than C.

If well written Assembly typically executes efficiently and requires less code space than does C.

It could be said C is efficient when referring to time to completion for a project. C is faster to write and given the same time period a C programmer can get more done. Compared line to line C does more.

Both Assembly have their places and projects. High speed data interfaces, timing critical applications often demand the use of ASM. Slow control loops and less critically timed applications sometimes make C a more reasonable choice.

The reason for using ASM in timing critical situations is because you know exactly how long execution takes based on clock speed and number of instructions. In C you can't always be sure what the compiler will generate for given code and therefore can't assume timing to be accurate, your routine may take 5 instructions or 11.
 
I'm currently testing efficient random number generators with 8bit avr microcontrollers. This is one, not very efficient, rng I tested:

Code:
uint64_t
random64(void)
{
	v ^= (v>>21);
	v ^= (v<<35);
	v ^= (v>>4);
	return v + 2685821657736338717LL;
}

It took roughly 1400 cycles to execute on an 8bit avr. I have no intention to try write that in assembly, but I would be interested to hear some estimates of how efficient that could be if written in asm? All numbers and variables are uint 64.
My solution is, instead of wasting my time with asm, to use an AES crypto engine to generate 128bit random numbers.. it does the job in background in 375 cycles.

And a point about the efficiency of C and assembly. The truth is that C is only as efficient as the assembly code generated by the compiler. So far all compilers are better assemblers than I am..
 
C is so much easier to use for math stuff.

Like for a tacho;
rpm = (60000000 / period_us);

is one easy line in C even though rpm and period_us are 16bit variables and all the math is done in 32bit. That takes a few seconds to type in C but is a rather nasty piece fo code to make in asm.


MisterT-
uint64_t
random64(void)
{
v ^= (v>>21);
v ^= (v<<35);
v ^= (v>>4);
return v + 2685821657736338717LL;
}

Where did you get that RNG code from? It looks poor, what is the point of adding a large prime number right at the end but not blending it in to the algorithm? :eek: You may as well just add "5" to the end result.

There is a RNG here that generates very good entropy from a simple algorithm although it is not particularly time efficient; The Black Random number generator
 
It seems that hardly anyone codes in primarily assembly anymore, yet I've read pretty much everywhere that assembly code seems to be much more efficient than C.

There is a lot of nonsense written about assembly language which simply isn't true any more. For some things, writing your own assembly is the best solution. The situations I am thinking of are timing critical, where you need to know exactly how long a piece of code will take. Think delays as a basic example, then scale to parts of a real-time operating system. There are other situations where assembly is the correct tool, of course.

However, over the last 30 years there have been significant improvements in processor speed, processor features and compiler design that mean that properly written C is a better solution. To break these down really briefly:

Processor speed isn't to be ignored. For hobby or small run projects, an extra cost of 10c per processor really doesn't make a difference. Both Microchip and Atmel sensibly ensure that devices are pin-compatible with others in the same family. This argument also holds for internal RAM/ROM.

Processor features are very important. The 18F (and upward) PICs and AVRs are specifically designed for code written in C. Not an afterthought, or a few improvements here and there, the whole core includes features which give benefits to compiled code in C. You can read far more than I know about this in the datasheets (or on Wikipedia).

Lastly, it seems that many of the assembly language comments come from people who either love assembly (nothing wrong with that except the hidden bias) or who have no idea about compiler design. 30 years ago significant portions of certain code had to be written in assembly in order for them to work at a decent speed. This simply doesn't hold with all the research effort that has gone into producing fantastic toolchains like the GNU C Compiler. And bad code in assembly or C is bad code regardless of the language ;)

Other things I haven't considered range from code reuse (e.g. porting your graphic LCD driver to a totally different uC very quickly) to sanity. And I value what is left of my sanity. The most important thing is to write decent code in whatever language you are comfortable with. It doesn't particularly matter if that is C or assembly, though there are obvious benefits to both in different situations.
 
Great responses guys! Honestly I'm very new to programming and have no experience with C at all as I've never been able to figure it out. As such I have no opinion either way on it...just wanted to know what all the hoopla was about.

I've just discovered using macros...which once I have completed writing the macro library is gonna make coding assembly so much less time consuming than it has been...ESPECIALLY for bank switching.

One of these days I'll get on the C band wagon. What are some good resources for learning C for first timers?
 
Last edited:
C is so much easier to use for math stuff.

Like for a tacho;
rpm = (60000000 / period_us);

is one easy line in C even though rpm and period_us are 16bit variables and all the math is done in 32bit. That takes a few seconds to type in C but is a rather nasty piece fo code to make in asm.


MisterT-

Where did you get that RNG code from? It looks poor, what is the point of adding a large prime number right at the end but not blending it in to the algorithm? :eek: You may as well just add "5" to the end result.

There is a RNG here that generates very good entropy from a simple algorithm although it is not particularly time efficient; The Black Random number generator

The RNG I posted (the code is missing the initialization) is from the book "Numerical Recipes - The Art of Scientific Computing, 3rd edition". In the book it says: "It has a period of “only” 1.8e19, so it should not
be used by an application that makes more than 10^12 calls. With that restriction, we think that it will do just fine for 99.99% of all user applications".

I don't know the point of adding the large prime number, but the idea behind "xorsift" random number generator is developed by Marsaglia https://www.jstatsoft.org/v08/i14/paper
 
Optimizing compilers can compact code in ways that no rational human would. Optimized code can be smaller then hand coded assembly. When people write ASM it has to be readable and maintainable. The optimizer is free to play whatever trick it can do its job.

People who choose to program in environments with real time or simulated debugging often have tools that let them easily count instructions and time. Simulators, logic analyzers, and emulators are the major tools that allow them to do so.
 
... Optimized code can be smaller then hand coded assembly...
With qualifiers...

For example, it's just not possible for a compiler to know that you've limited the range of values in a "char" variable to 0..63 (6 bits). My hand coded assembly would simply use two 'rlncf' instructions to multiply the value by four but there's no way for the compiler to know that it can do that...
 
Last edited:
Hi,

Well you have just had a fair cross section of opinions there - the only thing to add is that for the high level projects like USB, CAN, Ethernet etc then Microchips firmware is all in C, so long term you may have to use it.

However learning assembler will give you an excellent insight into the Pic but rather than suffer the bank and page sel problems of the 16F chips try using the 18F instead, so much easier; perhaps not so much code examples around for the 18F but lo cost chips like the 4520 or 4620 have masses of memory and features for both assembler and C.


If you must use the 16F, macros are handy but many short cuts have already been done like ' Banksel'
 
There have been other languages that were in theory better than C for higher level embedded programming, "Modula 2/ADA" are examples but C with all the warts gets the job done.

Other languages do have variable type subranges that you could tell the compiler to limit the values to 0..63 in a variable and it might optimize it the same way as the assembly example.

I used Modula-2 over 20 years ago to write multitasking software for the Atari ST , it's a shame the language is mainly dead.
 
I can read C but it takes me awhile. It looks and feels like a language written in 1950 by engineers for engineers when computers had little memory and ran with tubes.
 
EE I'll let you no if they teach C first then asm I'll be a EE in 3 years I'm starting computer science first
 
Last edited:
Hi,

Well you have just had a fair cross section of opinions there - the only thing to add is that for the high level projects like USB, CAN, Ethernet etc then Microchips firmware is all in C, so long term you may have to use it.

However learning assembler will give you an excellent insight into the Pic but rather than suffer the bank and page sel problems of the 16F chips try using the 18F instead, so much easier; perhaps not so much code examples around for the 18F but lo cost chips like the 4520 or 4620 have masses of memory and features for both assembler and C.


If you must use the 16F, macros are handy but many short cuts have already been done like ' Banksel'

I disagree with the 'run from Banksel' approach. It's not such a big deal. Further, learning to program with masses of memory to use will get u bloat code for sure. Then bloat code takes up more cycles so then u have to use a faster clocked chip etc. Ultimately u can end up being a programmer who can't program efficiently or have habits to 'unlearn'. If u can work with the midrange chips at least try it...the challenges u face will serve u well in all your projects.
 
I know I will get **** for this but:

It costs far far more to maintain code then it does to write it.

Learn to write quality code that is easy to read and maintain. Leave the code size issue up to the compilers. If you want tighter code buy a better compiler.

At this point people will think, with micro controllers we do not have code maintenance. Unless it is pure crap most code gets revised or borrowed from to produce future products.

If you want tight code read and learn about your compilers optimization. If you think you can do better on a bit of code look at the compilers asm for it and with your trick in place. In some cases the user optimization can screw up the compilers ability to optimize the code around it and result in larger code.

As hobbyist we can do as we please. But we have choices.
 
There is a RNG here that generates very good entropy from a simple algorithm although it is not particularly time efficient; The Black Random number generator

How do you (Mr RB) define "very good entropy"? Have you tested your Black RNG with some test algorithms like Diehard or the tests recommended by NIST? Also, you claim that the Black RNG generates pure random numbers that cannot be predicted.. How it is impossible to predict something that your algorithm just generated? And how is "unbreakable encryption" useful to anybody? Every encryption algorithm must have a method to decrypt the data, so by definition unbreakable encryption is impossible (or useless).

Sorry for the off-topic.
 
Last edited:
How do you (Mr RB) define "very good entropy"? Have you tested your Black RNG with some test algorithms like Diehard or the tests recommended by NIST? Also, you claim that the Black RNG generates pure random numbers that cannot be predicted.. How it is impossible to predict something that your algorithm just generated? And how is "unbreakable encryption" useful to anybody? Every encryption algorithm must have a method to decrypt the data, so by definition unbreakable encryption is impossible (or useless).

Sorry for the off-topic.

Computers don't do "random", I don't think Mr RB suggested the Black RNG was pure random, just that it had better entropy.

Breaking encryption and reversing (decrypting) it are two different things. With random or good pseudo-random seeds, encryption with no predictable patterns can hopefully be obtained, this makes it very difficult to break/crack (Provided you're using a decent algorithm). Breaking encryption suggests you've found a weakness, a shortcut to the end zone, you side-stepped knowing the cipher key. If you know the key you're not breaking the encryption, you're decrypting it.
 
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top