c standard functions fully optimized [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
c89
gcc (GCC) 4.7.2
Hello,
I am looking at some string functions as I need to search for different words in a sentence.
I am just wondering are the c standard functions fully optimized.
For example the functions like these:
memchr, strstr, strspn, strchr, etc
In terms of high performance as that is what I need. Is there anything better?
Regards,

You will almost certainly find that the standard library functions have been optimised as much as they can, and they will probably outdo anything you code up in C.
Note that this is for the general case. If there is some restriction you're able to put on the functions, or some extra piece of information you have on the data itself, you may be able to get your code to run faster, since you have the advantage of that restriction or information.
For example, I've written C code for malloc that blew a library-supplied malloc away because I knew the application would never ask for more than 256 bytes so I just gave 256 bytes on every request. Yes, that was a waste of memory but it allowed speed improvements beyond the general case.
But, for the general case, you're better off sticking with the supplied stuff.

Fully optimized? Optimized for what?
Yes, C functions of stdlib written to be very efficient and were tested/debugged for a years, so you definitely shouldn't worry about most of them.

Assuming, that you always align your data to 16-byte boundaries and allocate every time about 16 bytes extra or so, it's definitely possible to speed up most stdlib routines.
But assuming that eg. strlen is not known in advance, or that reading just one byte too much can cause a segmentation fault, I wouldn't bother.

Related

Data structures layout [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a disagreement with my colleague about sending/receiving a data structure between two machines (Also with different compilers) by UART.
Our data structure has several simple variable types as its fields (like int32, uint8 and etc).
In his opinion, to have a data structure with the same sequence and alignment in their fields, we have to use serializer and deserializer. Otherwise, Our code has the potential of different struct layout between two sides.
But I did it without using serializer/deserializer many times and never saw any problem.
I think using from the #pragma pack(...), guarantee our purpose. Because of most differences in each compiler (In data structures compiling) occurs in fields alignment due to padding for speedup or size optimization. (Ignore the different of endianness).
For more details, We want to send/receive a struct between a Cortex-M4 (IAR) and PC (Qt in windows) by UART currently.
Am I in a wrong way? Or my friend?!
This is, I'm afraid, fundamentally a question of opinion, that can never be fully resolved.
For what it's worth, I am adamantly, vociferously with your colleague. I believe in writing explicit serializers and deserializers. I don't believe in blatting out an in-memory data structure and hoping that the other side can slurp it down without error. I don't believe in ignoring endianness differences. I believe that "blatting it out" will inevitably fail, in the end, somewhere, and I don't want to run that risk. I believe that although the explicit de/serializers may seem to be more trouble to write up front, they save time in the long run because of all the fussing and debugging you don't have to do later.
But there are also huge swaths of programmers (I suspect a significant majority) who agree entirely with you: that given enough hacking, and suitable pragmas and packing directives, you can get the "blat it out" technique to work at least most of the time, and it may be more efficient, to boot. So you're in good company, and with as many people as there are out there who obviously agree with you, I can't tell you that you're wrong.

Questions about C as an intermediate language [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing a language that compiles to C right now, and when I say IL I mean as in C is the language I write the code as to then generate assembly by another c compiler, e.g. gcc or clang.
The C code I generate, will it be more beneficial to:
If I do some simple opt passes (constant propagation, dead code removal, ...) will this reduce the amount of work the C compiler has to do, or make it harder because it's not really human C code?
If I were to compile to say three-address code or SSA or some other form and then feed this into a C program with functions, labels, and variables - would that make it easier or harder for the C compiler to optimize?
Which kind of link together to form the following question...
What is the most optimal way to produce good C code from a language that compiles to C?
Is it worth doing any optimisations at all and leaving that to the compiler?
Generally there's not much point doing peephole type optimisations because the C compiler will simply do those for you. What is expensive is a) wasted or unnecessary "gift-wrapping" operations, b) memory accesses, c) branch mispredictions.
For a), make sure you're not passing data about too much, because whilst C will do constant propagation, there's a limit to how far it can detect that two buffers are in fact aliases of the same underlying data. For b) try to keep functions short and operations on the same data together, also limit heap memory use to improve cache performance. For c), the compiler understand for loops, it doesn't understand goto loops. So it will figure that
for(i=0;i<N;i++)
will usually take the loop body, it wont figure that
if(++i < N) goto do_loop_again
will usually take the jump.
So really the rule is to make your automatic code as human-like as possible. Though if it's too human-like, that raises the question of what your language has to offer that C doesn't - the whole point of a non-C language is to create a spaghetti of gotos in the C source, a nice structure in the input script.

Use C++ possibilities in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
It might be a silly question, but I'm interested in it very much. Is it possible to implement operator new, dynamically expanding arrays, classes in pure C?
Any links or code examples will be appreciated.
new: #define new(type) malloc(sizeof(type)) (have to call it using function syntax, like struct stat *st = new(struct stat))
dynamically expanding arrays: realloc plus some custom array-manipulation functions (like push_back, etc.) - this is commonly implemented by third-party C utility libraries (and, as #Mgetz points out, some compilers have built-in extensions for it)
classes: structs with function pointer members (this is very common in several projects, such as the Linux kernel)
You might want to look at GObject, which is a C library providing some object-oriented features to C. Also see the dozens of hits you get for googling "Object-Oriented C".
A quick google search revealed this:
http://ooc-coding.sourceforge.net/
Haven't read it through but it sounds like what you're after.
Yes, it is possible (common?) to implement object orientedness in C - or at least the bits that are especially needed.
An example is a once created a garbage collector by storing the pointers to malloced memory and the free function in linked lists.
The best thing about C is that it just works and there is almost zero overhead. The more work a language does for you automatically can mean there is a lot more overhead - though this is not always the case.
It depends if it is OK for you to reimplement the compiler.
If it's ok - you can do whatever you wish, otherwise:
new - as an operator - no, but you can define a function + macros that will simulate it.
classes - yep, you can. you may simulate it pretty closely with static functions and an array of pointers to functions. But there will be no overloading.
expanding arrays - yes, with the classes simulation above.

Is it a good practice to write multiple concise statements in one line? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am prone to writing code like this:
if (*t) while (*++t);
It reads: if string t does not start with /0, then move to the end.
Note the while loop has no body, so the semicolon terminates it.
I'd like to know if it is good practice to do this? Why and why not?
C is one of the oldest popular language in use today. I believe there's a good chance of finding one or more established style guide(s).
I know that Google has one for their C++ open source projects - http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Can anyone point me to resources on why or why not write code in certain manner?
Usually it is a good practice to write separate lines of code. Like in case of large pieces of code, debugging is clearer if we write code in separate lines.
It depends! Who is going to have to read and maintain this code? Coding standards exist for two major reasons:
To make code more readable and maintainable. When there are multiple developers, it makes code more consisent (which is more readable).
To discourage common errors. For example, a standard might require putting literals first in conditionals to discourage the assignment-as-comparison bug.
How do these goals apply to your specific code? Are you prone to making mistakes? If this is Linux kernel code, it's a lot more tolerable to have code like this than if it's a web app maintained by entry level programmers.
It reads: if string t does not start with /0, then move to the end.
Then consider putting a comment on it that says that.
Surprisingly - it is usually more expensive to maintain code over time than to write it in the first place. Maintenance costs are minimized if code is more readable.
There are three audiences for your code. You should think of how valuable their time is while you are formatting:
Fellow coders, including your co-workers and code-reviewers. You
want these people to have a high reputation of you. You should write code that is easily understandable for them.
Your future self. Convoluted code may be obvious while you are
writing it, but pick it up again in two weeks, and you will not
remember what it means. The 'concise' statement that you wrote in 10
minutes will someday take you 20 minutes to decipher.
The Optimizing Compiler, which will produce efficient code no matter
whether your line is concise or not. The compiler does not care - try to save time for the other two. (Cue angry remarks about this item. I am in favor of writing efficient code, but concise styles like the one we are describing here will not affect compiler efficiency.)
Bad practice, because not easy to parse. I'd do
while (*t) ++t;
and let the compiler do the tiny bit of optimization.
The textual translation of it reads even shorter than yours
advance t until it points to a 0
Although you can write some pretty clever code in one line in C, it's usually not good practice in terms of readability and ease of maintenance. What's straightforward for you to understand may look completely foreign to someone maintaining your code in future.
You need to strike a balance between conciseness and readability. To this end, it's usually better to separate the code out so each line does one thing.

Are function pointers evil? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have been told by more senior, experienced and better-educated programmers than myself that the use of function-pointers in c should be avoided. I have seen the fact that some code contains function pointers as a rationale not to re-use that code, even when the only alternative is complete re-implementation. Upon further discussion I haven't been able to determine why this would be. I am happy to use function pointers where appropriate, and like the interesting and powerful things they allow you to do, but am I throwing caution to the wind by using them?
I see the pros and cons of function pointers as follows:
Pros:
Great opportunity for code modularity
OO-like features in non-OO c (i.e. code and data in the same object)
How else could you reasonably implement a callback?
Cons:
Negative impact to code readability - not always obvious what function is actually called when a function pointer is invoked
Minor performance hit compared to a direct function call
I think Con # 1. can usually reasonably be mitigated by well chosen symbol names and good comments. And Con # 2. will in general not be a big deal. Am I missing something - are there other reasons to avoid function pointers like the plague?
This question looks a little discussion-ey, but I'm looking for good reasons why I shouldn't use function pointers, not opinions
Function pointers are not evil. The main times you "shouldn't" use them are when either:
The use is gratuitous, i.e. not actually needed for what you're doing, or
In situations where you're writing hardened code and the function pointer might be stored at a location you're concerned may be a likely candidate for buffer overflow attacks.
As for when function pointers are needed, Adam's answer provided some good examples. The common theme in all those examples is that the caller needs to be able to provide part of the code that runs from the called function. Without function pointers, the only way you could do this would be to copy-and-paste the implementation of the function and change part of it to call a different function, for every individual usage case. For qsort and bsearch, which can be implemented portably, this would just be a nuisance and hideously ugly. For thread creation, on the other hand, without function pointers you would have to copy and paste part of the system implementation for the particular OS you're running on, and adapt it to call the function you want called. This is obviously unacceptable; your program would then be completely non-portable.
As such, function pointers are absolutely necessary for some tasks, and for other tasks, they are a major convenience which allows general code to be reused. I see no reason why they should not be used in such cases.
No, they're not evil. They're absolute necessary in order to implement various features such as callback functions in C.
Without function pointers, you could not implement:
qsort(3)
bsearch(3)
Window procedures
Threads
Signal handlers
And many more.

Resources