11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,

Slides:



Advertisements
Similar presentations
ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
Advertisements

C-LISP. LISP 2 Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT).John McCarthyMassachusetts Institute.
Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
Kernighan/Ritchie: Kelley/Pohl:
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages It’s elegant, minimal, can be.
Lisp – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
CMSC 471 LISP. Why Lisp? Because it’s the most widely used AI programming language Because it’s good for writing production software (Graham article)
Introductory Lisp Programming Lecture # 2 Main Topics –Basic Lisp data types –Lisp primitives –Details of list handling Cons cells (boxes) & their representation.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester, 2010
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration.
General pattern for selecting some elements of a list This negatives example illustrates a general pattern: If you want a function which selects some elements.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
LISP A brief overview. Lisp stands for “LISt Process” –Invented by John McCarthy (1958) –Simple data structure (atoms and lists) –Heavy use of recursion.
COMP 205 – Week 11 Dr. Chunbo Chu. Intro Lisp stands for “LISt Process” Invented by John McCarthy (1958) Simple data structure (atoms and lists) Heavy.
CSE 341, S. Tanimoto Lisp Data Structures - 1 Data Structures in Lisp 0. Collections of associations, association lists. 1. Creating graphs with conses.
LISP 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
Conditionals and Recursion "To iterate is human, to recurse divine." - L. Peter Deutsch.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Allegro CL Certification Program Lisp Programming Series Level I Session Overview of Common Lisp.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
Functional Programming 02 Lists
PRACTICAL COMMON LISP Peter Seibel 1.
Mitthögskolan 10/8/ Common Lisp LISTS. Mitthögskolan 10/8/2015 2Lists n Lists are one of the fundamental data structures in Lisp. n However, it.
1 Lists in Lisp and Scheme. 2 Lists are Lisp’s fundamental data structures. Lists are Lisp’s fundamental data structures. However, it is not the only.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
Lecture 2-1CS250: Intro to AI/Lisp Intelligent Agents Lecture 3-2 October 14 th, 1999 CS250.
Common lisp A functional programming language. Useful URL:
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
CS535 Programming Languages Chapter - 10 Functional Programming With Lists.
PRACTICAL COMMON LISP Peter Seibel 1.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
Miscellaneous Topics Packages –Provide separable name spaces for functions, constants, macros –We can encapsulate code in packages like classes in Java.
PRACTICAL COMMON LISP Peter Seibel 1.
PRACTICAL COMMON LISP Peter Seibel 1.
Compiling “premature optimization is the root of all evil.” -Donald Knuth.
Operating on Lists Chapter 6. Firsts and Seconds n Transforming list of pairs into two lists –(firsts ‘((1 5) (2 6) (3 7)))  (1 2 3) –(seconds ‘((1 5)
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
Lists CSC 358/ Outline Lab #1 / Homework #1 Lists A question List Internals of Lists List operations Extended Example.
Basic Introduction to Lisp
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Object Lifetime and Pointers
Data Types In Text: Chapter 6.
Tail Recursion.
Intelligent Agents Lecture 3-2 October 14th, 1999 CS250 Lecture 2-1
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
Lists in Lisp and Scheme
J.E. Spragg Mitthögskolan 1997
Modern Programming Languages Lecture 21 Fakhar Lodhi
Binding Times Binding is an association between two things Examples:
Modern Programming Languages Lecture 20 Fakhar Lodhi
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Abstraction and Repetition
Common Lisp II.
More Scheme CS 331.
LISP primitives on sequences
Presentation transcript:

11 Speed & Debug

 Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage, you can trade speed for convenience. Then, you can refine critical portions to make them faster once your program begins to crystallize

 Optimization  Should be focused on bottlenecks  Should not begin too early  Should begin with algorithms  Programs tend to have a few bottlenecks that account for a great part of the execution time  “Most of the running time in none-IO-bound programs is concentrated in about 3% of the source text. Optimizing these parts of the program will make it run noticeably faster; optimizing the rest of the program will be a waste of time on comparison.”, by Knuth

 Optimize the program from the top  Make sure that you’re using the most efficient algorithm before you resort to low-level coding tricks  Decisions about algorithms have to be made early

 Five parameters control the way your code is compiled  Speed: the speed of the code produced by the compiler  Compilation-speed: the speed at which your program will be compiled  Safety: the amount of error-checking done in the object code  Space: the size and memory needs of the object code  Debug: the amount of information retained for debugging

 The compilation parameters are not real variables. They are assigned weights from 0 (unimportant) to 3 (most important) in declarations  (defun bottlenect (…) (do (…) (…) (do (…) (…) (declare (optimize (speed 3) (safety 0))) …)))  Add such declarations until the code was finished and tested

 Inline function  Without the cost of calling functions  Similar to macros  Macro ▪ Since macros use mere textual substitution, this may result in unintended side-effects and inefficiency due to re-evaluation of arguments and order of operations ▪ Compiler errors within macros are often difficult to understand, because they refer to the expanded code  Recursive functions cannot be inlined  If an inlined function is redefined, we have to recompile any function that calls it

 (declaim (inline single?)) (defun single? (lst) (and (consp lst) (null (cdr lst))))  (defun foo (x) (single? (bar x)))  When foo is compiled (defun foo (x) (let ((lst (bar x))) (and (consp lst) (null (cdr lst)))))

 In most languages, you have to declare the type of each variable, and the variable can only hold values of that type → strongly typed language  Common List uses manifest typing (run-time typing)  Type information is attached to the data objects  Type information is used at run-time  Variables can hold objects of any type  We have to pay for this flexibility in speed ▪ The function have to look at the types of each of its arguments at run- time  If we just want one type, say, fixnum, this is an inefficient way

 In Common Lisp, type declarations are completely optional  Global declarations are made with declaim  (declaim (type fixnum *count*)) ;type can be omitted  Local declarations are made with declare  (defun poly (a b x) (declare (fixnum a b x)) (+ (* a (expt x 2)) (* b x)))

 Type declarations are particularly important for the contents of complex objects, including arrays and structures  Declarations can improve efficiency The compiler can determine the types of arguments to functions and represent these objects more efficients ▪ If nothing is known about the type of elements an array will contain, it has to be represented in memory as a block of pointers ▪ If it is known that the array will only contain, say, double- floats, then the array can be represented as a block of actual double-floats

 (setf x (vector 1.234d d d0) y (make-array 3 :element-type ‘double-float) (aref y 0) 1.234d0 (aref y 1) 2.345d0 (aref y 2) 3.456d0)

 (setf a (make-array ‘( ) :element-type ‘single-float :initial-element 1.0)) (defun sim-elts (a) (declare (type (simple-array single-float ( )) a)) (let ((sum 0.0)) (declare (type single-float sum)) (dotimes (r 1000) (dotimes (c 1000) (incf sum (aref a r c)))) sum))

 > (compile-file “..\\test\\declare.lsp”)  > (load “..\\test\\declare.fas”)  > (time (sum-elts a)) Real time: sec. Run time: sec. Space: Bytes GC: 1, GC time: sec  > (compile-file “..\\test\\nodeclare.lsp”)  > (load “..\\test\\nodeclare.fas”)  > (time (sum-elts-nodeclare a)) Real time: sec. Run time: sec. Space: Bytes GC: 2, GC time: sec

 Dynamic allocation is slow  Programs that cons a lot tend to run slowly in Lisp implementations with bad garbage collectors  Until recently, most Lisp implementations have had bad garbage collectors  Efficient programs should cons as little as possible

 One of the easiest way is to use destructive functions  When you know it’s safe to modify a list, you can use delete instead of remove, nreverse instead of reverse, and so on SAFEDESTRUCTIVE append reverse remove remove-if remove-duplicates subst subst-if union intersection set-difference nconc nreverse delete delete-if delete-duplicates nsubst nsubst-if nunion nintersection nset-difference.

 Use a pre-allocated vector instead of building it using conses  > (setf *print-array* t) T > (setf vec (make-array 10 :fill-pointer 2 :initial-element nil)) #(NIL NIL) > (length vec) 2 > (vector-push ‘a vec) 2 > vec #(NIL NIL A) > (vector-pop vec) A > vec #(NIL NIL)

 svref is more efficient than aref  eq is more efficient than eql  (reduce #’+ ‘(1 2 3)) is more efficient than (apply #’+ ‘(1 2 3))

 trace  (defun count-atoms (expression) (if (atom expression) 1 (+ (count-atoms (first expression)) (count-atoms (rest expresstion)))))  > (count-atoms ‘((this is) (a test))) 7 ;we expect 4

 > (trace count-atoms) ;; Tracing function COUNT-ATOMS. (COUNT-ATOMS)  (count-atoms '((this is) (a test)))

2. Trace: (COUNT-ATOMS '((THIS IS) (A TEST))) 3. Trace: (COUNT-ATOMS '(THIS IS)) 4. Trace: (COUNT-ATOMS 'THIS) 4. Trace: COUNT-ATOMS ==> 1 4. Trace: (COUNT-ATOMS '(IS)) 5. Trace: (COUNT-ATOMS 'IS) 5. Trace: COUNT-ATOMS ==> 1 5. Trace: (COUNT-ATOMS 'NIL) 5. Trace: COUNT-ATOMS ==> 1 4. Trace: COUNT-ATOMS ==> 2 3. Trace: COUNT-ATOMS ==> 3 3. Trace: (COUNT-ATOMS '((A TEST))) 4. Trace: (COUNT-ATOMS '(A TEST)) 5. Trace: (COUNT-ATOMS 'A) 5. Trace: COUNT-ATOMS ==> 1 5. Trace: (COUNT-ATOMS '(TEST)) 6. Trace: (COUNT-ATOMS 'TEST) 6. Trace: COUNT-ATOMS ==> 1 6. Trace: (COUNT-ATOMS 'NIL) 6. Trace: COUNT-ATOMS ==> 1 5. Trace: COUNT-ATOMS ==> 2 4. Trace: COUNT-ATOMS ==> 3 4. Trace: (COUNT-ATOMS 'NIL) 4. Trace: COUNT-ATOMS ==> 1 3. Trace: COUNT-ATOMS ==> 4 2. Trace: COUNT-ATOMS ==> 7 7

 (defun count-atoms (expression) (cond ((atom expression) 1) ((null expression) 0) (t (+ (count-atoms (first expression)) (count-atoms (rest expression))))))  > (count-atoms ‘((this is) (a test))) 7

 (defun count-atoms (expression) (cond ((null expression) 0) ((atom expression) 1) (t (+ (count-atoms (first expression)) (count-atoms (rest expression))))))  > (count-atoms ‘((this is) (a test))) 4  > (untrace count-atoms)

 > (dribble “record.txt”) ; 記錄在 toplevel 的過程 … … > (dribble) ;stop dribbling  > (ed “record.txt”)

 Write a Lisp program with at least 15 functions  Due June 30  Report  Source code  Demo