473,782 Members | 2,448 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

useful tips on how to write your C codes more efficiently

Hi,

I'm writing some C codes to run simulations.
I'm wondering if there is a website that may contain useful information
on how to make one's code run more efficiently and in a
computational-time-saving manner. Specifically, what I'd like to know
is if there're any useful tips about writing your codes more
efficiently. One such useful tip is that we can use the "switch"
statement instead of multiple "if-else" statements; another is that if
you wish to put some information in an array, and that you foresee the
array is not going to be too big, then it probably pays to just define
a fixed size array instead of using "malloc."

So, I'm wondering if anybody knows of a website that may contain
such helpful tips to help a mid-level programmer like me write codes
better.

Thanks.

-Ed

Nov 14 '05 #1
7 2329

ey**@ece.cornel l.edu wrote:
Hi,

I'm writing some C codes to run simulations.
I'm wondering if there is a website that may contain useful information on how to make one's code run more efficiently and in a
computational-time-saving manner. Specifically, what I'd like to know
is if there're any useful tips about writing your codes more
efficiently. One such useful tip is that we can use the "switch"
statement instead of multiple "if-else" statements; another is that if you wish to put some information in an array, and that you foresee the array is not going to be too big, then it probably pays to just define a fixed size array instead of using "malloc."

So, I'm wondering if anybody knows of a website that may contain
such helpful tips to help a mid-level programmer like me write codes
better.

Thanks.

-Ed


Have a look at the following link:
http://www.eventhelix.com/RealtimeMa...AndCPPCode.htm

In fact I also asked this question on this newsgroup and most of them
suggested that "profiling is the best technique".

Nov 14 '05 #2
ey**@ece.cornel l.edu wrote:
Hi,

I'm writing some C codes to run simulations.
I'm wondering if there is a website that may contain useful information on how to make one's code run more efficiently and in a
computational-time-saving manner. Specifically, what I'd like to know
is if there're any useful tips about writing your codes more
efficiently.
1. Choose algorithms with appropriate complexity for the task at hand.
2. Code the algorithms simply and portably.
3. Compile the code with the appropriate optimization flags. Run it.

Is it fast enough? Probably. If it's not, then:

4. Profile the code. Identify the main bottlenecks.
5. Refactor the bottleneck code. Repeat #4 until no further gains are
made.

If it's still not fast enough, then:

6. Take advantage of platform-specific features. Isolate
platform-specific code.

7. Take advantage of CPU-specific instructions via inline assembly
code (which itself is not part of C, but a common extension). Again
isolate as much as possible.

One such useful tip is that we can use the "switch"
statement instead of multiple "if-else" statements; another is that if you wish to put some information in an array, and that you foresee the array is not going to be too big, then it probably pays to just define a fixed size array instead of using "malloc."
You'd be surprised. On many fast modern machines, it won't make as big
of a difference as you think, unless you're executing it in a tight
loop. Write simple and idiomatic C code.

So, I'm wondering if anybody knows of a website that may contain
such helpful tips to help a mid-level programmer like me write codes
better.


If your goal is to write C code better, simply read comp.lang.c daily,
code actively, and refactor relentlessly.

Mark F. Haigh
mf*****@sbcglob al.net

Nov 14 '05 #3
On 19 May 2005 19:21:57 -0700, ey**@ece.cornel l.edu wrote:
Hi,

I'm writing some C codes to run simulations.
I'm wondering if there is a website that may contain useful information
on how to make one's code run more efficiently and in a
computationa l-time-saving manner. Specifically, what I'd like to know
is if there're any useful tips about writing your codes more
efficiently. One such useful tip is that we can use the "switch"
statement instead of multiple "if-else" statements; another is that if
you wish to put some information in an array, and that you foresee the
array is not going to be too big, then it probably pays to just define
a fixed size array instead of using "malloc."

So, I'm wondering if anybody knows of a website that may contain
such helpful tips to help a mid-level programmer like me write codes
better.


The following document contains some helpfull tips :

http://www.agner.org/assem/pentopt.pdf

Chapter 3 is about optimizing C++ (but lots of it also goes for C).
Chapter 2 is also quite helpfull.

Of course, it's important to use the best algorithm before tweaking it
but in order to tweak one needs to know some basics of computer
architecture (knowing about how caches work, branch prediction,
pipelines and the relative costs of instructions).

In the end, you might need to resort to Assembly programming for the
hotspots in your program (of course, it isn't portable).

Nov 14 '05 #4
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
Mark F. Haigh <mf*****@sbcglo bal.net> wrote:

5. Refactor the bottleneck code. Repeat #4 until no further gains are
made.


You are using the word refactor in an odd way. Unless I am sadly
misinformed, refactoring is more about changing source code
to improve readability and maintainability , and to remove multiple
implementations of the same idea throughout a large project.

The wiki for refactoring, http://en.wikipedia.org/wiki/Refactor
has a list of useful kinds of refactoring and none of them specify
efficiency, speed, or execution time as benefits.

I admire your drive to refactor ("it's a good thing"), but moving
code around in and of itself will not make anything run faster. Some
optimizations are infact unfactoring--loop unrolling, manual inlining,
and grouping functions or data for cache friendliness for example.

The rest of your advice was quite good, so I'm just nitpicking.
--
7842++
Nov 14 '05 #5
In article <Ozsje.267$Xh.1 36@fed1read07>,
an******@exampl e.com (Anonymous 7843) wrote:
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
Mark F. Haigh <mf*****@sbcglo bal.net> wrote:

5. Refactor the bottleneck code. Repeat #4 until no further gains are
made.


You are using the word refactor in an odd way. Unless I am sadly
misinformed, refactoring is more about changing source code
to improve readability and maintainability , and to remove multiple
implementations of the same idea throughout a large project.


The term "refactorin g" is generally used for _anything_ that rearranges
the code in any way without changing its meaning. Refactoring should
obviously only used when it improves _something_ (even if it only
improves job security), but the thing that is improved may very well be
performance at the cost of readability and maintainability .
Nov 14 '05 #6
On Fri, 20 May 2005 21:23:58 GMT, an******@exampl e.com (Anonymous
7843) wrote:
I admire your drive to refactor ("it's a good thing"), but moving
code around in and of itself will not make anything run faster. Some
optimization s are infact unfactoring--loop unrolling, manual inlining,
and grouping functions or data for cache friendliness for example.


Actually, moving code around may improve performance if it breaks up
dependancy chains. In today's pipelined architectures, this can speed
up things considerably.

Of course, breaking up dependancy chains has a way to make code less
readable :-)

Nov 14 '05 #7

<ey**@ece.corne ll.edu> wrote
One such useful tip is that we can use the "switch"
statement instead of multiple "if-else" statements; another is that if
you wish to put some information in an array, and that you foresee the
array is not going to be too big, then it probably pays to just define
a fixed size array instead of using "malloc."

These sorts of tips are of limited use. In the inner loop of a
computationally intensive program, it might be the case that you can get a
worthwhile performance increase by replacing an if .. else ladder by a
switch, or a call to malloc() by a fixed size array. It depends on the
compiler.

The first thing you should do is look at the algorithm. Sometimes you can
reduce the big O running time of the algorithm - the classic case is
replacing bubble sort which is O(N^2) with qsort() which is O(Nlog N). In
other cases you can get rid of big constant factors, for instance
calculating the length of string once and storing it rather than calling
strlen() twice.

The main reason most real programs run too slowly, however, is time spent
reformatting data and going through layers of indirection. Here there is a
tradeoff between readability and testability, and perfomance. For instnace,
to calculate a standard deviation, the natural thing would be to write a
function called stdev() which takes an array of doubles as an argument.
However you might want the standard deviation of some numbers which are low
integers, and members of a bigger structure. So calling malloc() to allocate
a temporary array, passing through to convert the integers to doubles,
calling stdev(), and then calling free() to get rid of the array, is a big
overhead. By writing a customised routine, you can probably double
performance.

A related issue is hardware interaction. It is less of a problem these days,
but in the old MS DOS days you weren't supposed to write directly to screen
memory, but everyone did, because using the conio functions was just too
slow. There is often a compromise between going through layers of
indirection so that your program works well with other programs, and
accessing things directly for speed.
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1324
by: Henry S. Thompson | last post by:
I'm pleased to announce that a showcase of Markup Technology's high-performance MT Pipeline product is now available at http://www.markup.co.uk:8888/ The showcase provides online access to a range of useful XML transformations, some of which are difficult or even impossible to obtain elsewhere, which illustrate how XML pipelines enable complex XML operations to be easily specified and efficiently executed without writing a line of...
21
2620
by: Hattuari | last post by:
I'm learning C++ after having spent several years in the computer industry doing both system administration and engineering. I've written code in Perl, Bash, Pascal, Ada, C, Mathematica (hundreds of lines of OO code, not 1+1), JavaScript, Lisp, and Java, as well as C++. Each of these languages has it's strengths and weaknesses. My experience with C++ has shown me that it is by far the most difficult for me to learn. I have the sense...
9
2798
by: Harry | last post by:
I am accumulating over 80 pages per day into an archive that I will need to be able to present sequentially to viewers. Using html to viewing a page, then click on back to return to my archive index is so awkward it is not useful for my presentations. Can javascript be used to create a powerpoint like presentation of html files (with gif hyperlinks)sequentially from html page to page? Is so, could someone suggest where I could find a...
0
1125
by: Welman Jordan | last post by:
Hello, I would like to write a simple forum for my site, which enables some formating, like , , and some other BBS format code. For example, the user inputs this string in a multiline textbox, as the body of his/her post,
3
8535
by: Billy Smith | last post by:
I'm trying to write a little utility that will write some binary data to a file via a javascript and Windows Script Host under Windows XP. The only way to do this that I can find is to convert the binary data to text via String.fromCharCode() function and then write to the file with TextStream.Write(). But that function gives an "invalid parameter" error message when I try to write some ASCII codes to the file. I could understand if...
0
6176
MMcCarthy
by: MMcCarthy | last post by:
This is a list of technical site links that many of our experts find useful. They are often included in posts in answer to repeated questions so I am posting a list of them here for convenience. These sites are not advertisements and if any site here causes users any problems please let me know. They are only meant to include links that contain answers to frequently asked questions. Of course if there is anything on any of these sites...
4
1611
by: robert.waters | last post by:
Does anyone use modeling tools to determine the layout of a database before implementing it? If so, does the tool you use have the ability to generate the modeled tables (or at least generate create table SQL statements)? I have seen a few utilities, but they are pretty expensive and/or do not support access. Thanks.
6
1426
by: =?Utf-8?B?RWxlY3Ryb25pYzc1?= | last post by:
Hello, I program in C and c++ for 5+ years but I am still not satisfied with my development process. for a big MFC project I usually start by thinking what classes do I need then for each class I ask what function and variables do I need and I start writing codes. but many times at the middle of project I will realize that I could have written program somehow else that possibly was more user friendly or more efficient or,... and I start...
0
281
by: big bill | last post by:
- Using Anchoring and Docking http://tips-coding.blogspot.com/2008/10/net-using-anchoring-and-docking.html - Readonly Constants http://tips-coding.blogspot.com/2008/10/net-readonly-constants-in-dotnet.html - Copy Constructors http://tips-coding.blogspot.com/2008/10/net-copy-constructors-in-dotnet.html - Bind two controls to the same data source with
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.