Title: C Programming Basics for High Performance Computing
1C Programming Basics for High Performance
Computing
- A Short-Series Presentation by
- Evan Lee Turner
2For the Beginner
- This presentation is created for the beginning
programmer with little or no previous programming
knowledge. - Not everything is covered!
- Will emphasize how C works, what it can do, and
how best to write efficient C code. - Things you will not find in the manual
- Useful tools for HPC users
- Assume that you have taken the previous UNIX
course
3History of C
- Dennis Ritchie developed the C language with the
UNIX OS in the early 1970s. - UNIX and LINUX kernels are still developed in C
and assembly today.
4Why Use C?
- Scientific Applications
- C and FORTRAN remain the dominant programming
forces in scientific computing because of the
speed of execution. Performance libraries are
written in C. Parallel pragma language
extensions exist for C, C, and FORTRAN such as
openMP and MPI. - UNIX/LINUX Programming
- Since the OS and libraries are written in C there
is a natural transition to write applications for
Linux in C - Interoperability with Fortran
- Traditionally, scientists will use C to glue
together FORTRAN functions since C is easier to
develop and maintain
5My First Program
- include ltstdio.hgt
- int main()
-
- printf(hello world\n)
- return 1
6Variables
- Several basic datatypes exist in C to represent
data - typename variablename
- Defines a variable name and type. All variables
must be defined in C. - Examples
- int myInteger
- char myCharacter
7Integer Types
- Byte sizes for Lonestar Ranger.
- char c
- printf("u,u", (unsigned) sizeof c, (unsigned)
sizeof (int)) - int - 4
- long - 8
- char - 1
- short - 2
8Float Types
- The majority of scientific codes will use
floating-point data in double precision - float (single precision) 4 bytes
- double - 8 bytes
- long double 10 bytes
9Character Types
- char myName10
- Create a string variable called myName which
contains 10 elements - strcpy(myName, Evan)
- myName Evan ! Invalid syntax
10Assigning Values
- Why cant I assign a string to a value?
- Only scalar (a single value) can be assigned at a
time. A string is an array of values, and each
location must be assigned individually - Values are assigned by the assignment operator
. - Valid syntax
- char myChar
- int x
- X 3
- myChar x
- - notice here we can use
instead of
11Mathematical Operations
- increment decrement , --
- result
- result result 1
- Normal mathematical operations , -, divide /
- capture a remainder for integer numbers
- result sum 4 / result is 2 /
- Normally when an operation occurs on variables of
different type, the lesser type is promoted.
12Working with Strings
- Must use built-in functions to work with string
values - strcpy(destination, source)
- copies one string to another
- strcpy(name1, name2)
- copies contents of name2 into name1
- int strcmp(string1, string2)
- compares string1 with string2, returns an
integer less than, equal to, or greater than zero
if s1 is found, respectively, to be less than,
to match, or be greater than s2.
13Strings and Arrays
- A string is just a one-dimensional array of
characters - An array is defined as
- datatype name size
- int myarray6
- myArray0 54
- Places the integer 54 in the first position of
the array
14Functions
- functions()
- A function can be thought as a mini-program where
inputs are taken in and values returned - returnValue MyFunction(input)
- Some functions are defined by the system such as
printf(), scanf(), open(), or close(). User
defined functions are declared in the calling
program.
15Program Flow
- loops
- for(i 0 i lt num i)
- while(thisValueIsTrue)
- do while(thisValueisTrue)
- Conditionals
- if (valueIsTrue) do this.. else do this..
- nested if else statements are possible
16Constructing Logic
- Use in conditional statements (and loops)
- evaluation operators , gt, lt
- if (value1 gt value2)
- Logic and, or, not
- and operation, , !
- if (value1 gt value2 value3)
- Order of operation
- logic is processed first, then evaluations
- if((value1 gt value2) (value3))
17Advanced Control
- continue
- used in a for() loop will cause the current
iteration to stop and will start the next loop
iteration - break
- used to break outside of a loop or conditional
prematurely. - exit
- quits the program
18Swtich Statements
- Useful for constructing argument parsing instead
of using large if-else-if-else statements - switch(letter)
- case A printf(A is for apple\n)
- break
- case B printf(B is for Bob Garza\n)
- break
-
-
19Output
- printf, the all-in-one output function for C.
- printf (hello world\n)
- will output hello world to screen with a newline
- printf(my name is s\n, myName)
- output my name is and the contents of string
myName to screen with a newline
20Conversion Characters
- Printing values of all data types is possible
with conversion characters. Each conversion
character tells printf what kind of data is
expected to follow. - Common Characters
- d, i, u integer
- x hexadecimal
- f floating point number
- s string
- c character
21More printf Examples
- printf(My name is s and I am d years old\n,
myName, myAge) - Carriage control is provided by the backslash
- \n, newline
- \t tab
- \b backspace
- \\ produce a single backslash \
22Advanced Output
- printf() is a highly robust function that can
parse output effectively - printf("\n\nHOST\t\tR15s\tR1m\tR15m\tPAGES
\t\tMEM\tSWAP\tTEMP\n") - printf("s\t5.1f\t5.1f\t5.1f\t5.1fP/s\t4.fM\t
4.fM\t4.fM\n", - hostsi.hostName,hostsi.liR15S,hos
tsi.liR1M,hostsi.liR15M, - hostsi.liPG,hostsi.liMEM,hosts
i.liSWP,hostsi.liTMP) - produces the output
- HOST R15s R1m R15m PAGES
MEM SWAP TEMP - c21-208 1.0 1.0 1.0 2.1P/s
6468M 2021M 55776M
23Input
- Input can be handled with the scanf function
which behaves similarly to printf - scanf (d f, integer, float)
- Variables must be handed to scanf with the
address operator . In C the address operator
gives a variables address in memory, not the
value itself.
24Working with scanf
- scanf will parse standard input and match cases
that it finds. - gets (string)
- grabs all of the string input on the screen and
will save it in the array string - Later in the presentation we will see a better
way to do input processing
25Working with Files
- Manipulating files is easy and fun with C!
- / definitions /
- define NAMELIMIT 40
- FILE fptr
- char filenameNAMELIMIT
- / in code /
- fptr fopen(filename, r)
- if ( fptr NULL)
- perror(error openning file)
-
- fcose (fptr)
26Working with File Pointers
- File pointers can be manipulated in the same
fashion as I/O from the keyboard and to the
screen. - Instead of fprint fscanf can read and write to a
file pointer. - int item
- fscanf (fptr, d, item) / read one value /
- printf( d\n, item) / print item to screen
/
27fprintf() and fscanf()
- Usage is exactly the same as printf and scanf
except for specifying the file pointer in the
beginning of the satement. - fprintf(fptr, .)
- Incidentally, all input and output are file
pointers that can be manipulated. STDOUT is the
screen pointer. (STDIN is the input pointer) - fprintf(STDOUT, Hi there!)
- printf(Hi there!) / equivalent statement
/
28fopen() arguments
- FILE fptr
- fptr fopen( myfile, r)
- - Open file for reading
29Putting I/O together
- According to the MAN page for gets()
- BUGS
- Never use gets(). Because it is impossible to
tell without knowing the data in advance how
many characters gets() will read, and
because gets() will continue to store
characters past the end of the buffer, it is
extremely dangerous to use. It has been used to
break computer security. Use fgets() instead
30Best Practice
- ALWAYS be suspect of the input given from users
or other programs and use error cases! -
- char fgets(char s, int size, FILE stream)
- Good error detection aids in debugging and test
cases, program utility, and will extend program
life.
31Where to Look for Help
- The UNIX system manual
- man fprintf
- PRINTF(3)
Linux Programmer's Manual - NAME
- printf, fprintf, sprintf, snprintf,
vprintf, vfprintf, vsprintf, vsnprintf -
formatted output conversion - SYNOPSIS
- include ltstdio.hgt
- int printf(const char format, ...)
- int fprintf(FILE stream, const char
format, ...) - int sprintf(char str, const char format,
...) - int snprintf(char str, size_t size, const
char format, ...)
32Importance of Documentation
- A necessity of programmers!
- C comments
- // comments a single line - GNU gcc
- / comment
- a block
- of text /
33Using Brackets
- / What is wrong with this block? /
- while(true)
-
- for (i i lt 24 i 0)
-
- if ( i 5)
-
- printf(i is equal to 5)
-
We did not terminate this if() conditional with
another . The program would error on compile
time.
34Which would be best?
/ better still?? / while(true) for (i i lt
24 i 0) if ( i 5)
printf(i is equal to 5)
- / better? /
- while(true)
-
- for (i i lt 24 i 0)
-
- if ( i 5)
-
- printf(i is equal to 5)
-
-
-
How about?
Or even?
while(true) for (i i lt 24 i 0) if (
i 5) printf(i is equal to 5)
35less code is not always best
- The last example may not be the most readable,
but neither is the first. The best documentation
method is something in between the extremes. - Unless you are experienced, it is best to
terminate your blocks - while(true)
- for (i i lt 24 i 0)
- if ( i 5)
- printf(i is equal to 5)
- // END FOR
- // END WHILE (true)
36Self-Documenting Code
- Programmers create their own styles and
conventions. I tend to name variables as
firstwordSecondword and functions in Caps(). - myName, ourAddress, PrintTable()
- For the Love of UNIX and C make your variable
names stand for something other than
x1,xx1,zz2,t1,t2,t3 - Generally only loop counters and temp variables
should be named with junk titles - i,j,k, tmp,
- The term self-documentation refers to being able
to read a code without any extra comments
37Necessity of Good Style
- Self-Documentation and the position of code and
brackets are all separate of comments, but are
absolutely vital to clean, fast running code - Poorly documented code with bad style will lend
itself to bugs even if semantically correct
38More Advanced Stuff
- Parsing your command arguments
- when you run a program on the command line,
arguments that are passed to the program can be
parsed. This is VERY useful for dynamic input
such as input files. - In order to capture your arguments start a C
program with - int main(int argc, char argv)
-
39Example from lsuser.c
/ Process my argument List / if(argc gt 1)
if(strchr(argv1,'?')
strchr(argv1,'h')) PrintUsage()
if(strchr(argv1,'s'))
suppressNodes 1 if(strchr(argv1,'r'))
runningOnly 1
if(strchr(argv1,'a')) allJobs 1
if(strchr(argv1,'z'))
suppressNodesAll 1 if(strchr(argv1,'w'
))
40System Calls
- system()
- Call a UNIX system program externally
- system(clear) / clears the screen /
- note that this will break an MPI program on
lonestar - system calls are expensive computationally
- most system calls can actually be accomplished by
a similar C library. chmod, chown, chdir, rename
41Retrieving Environment Variables
- include ltstdio.hgt
- include ltstdlib.hgt
- / To shorten example, not using argp /
- int main (int argc, char argv, char envp)
-
- char home, host
- home getenv("HOME")
- host getenv("HOSTNAME")
- printf ("Your home directory is s on s.\n",
home, host) - return 0
42Signals
- Programs are given signals by the UNIX system to
quit or exit, and they also create signals when
errors occur - It is useful to be able to catch signals in
order to execute actions when bugs occur - extremely advanced programming methods (read the
manual before attempting this)
43Continuing after Signals
/ Example program by pipas_at_linux.pte.hu
This program is uninterruptable with CtrlC,
uses signal handler http//www.metalshell.co
m/ / include ltstdio.hgt include
ltsignal.hgt include ltunistd.hgt / The signal
handler function / void handler( int signal )
printf("Signal handler...\n") psignal(
signal, "Signal ") /handler/
main() / Registering the handler, catching
SIGINT signals / signal( SIGINT, handler
) / Do nothing / while( 1 )
printf("Running...\n") sleep(10)
/while/ /main/
44Power of Signals
- Graceful exits when things go wrong
- Program receives a kill signal while files are
open - print useful information such as an error code
- point fault locations such as functions or
procedures
45Manuals and References
- The C Programming Language by Brian W.
Kernighan and Dennis M. Ritchie - The C Bible
- Advanced Programming in the UINIX environment
by Stevens - The UNIX Bible
- UNIX System Programming by Haviland
- The UNIX Programming Environment by Kernighan
and Pike - http//www.metalshell.com/view/source/106/ -
example of signal handling