Pages

Saturday, December 26, 2015

Eclipse CDT, a C++ IDEs on Windows

In addition to VC++, a few open sourced C++ IDEs are also widely used on Windows: Code::Block and Eclipse CDT.

Eclipse CDT is available in Eclipse IDE for C++ Developers or as a plugin in Eclipse. Here is how to set up Eclipse CDT for C++11.
  • Install New Software... in Eclipse IDE for Java Developers            
        (web url: http://download.eclipse.org/tools/cdt/releases/8.8)
  • Install a C++ Compiler (e.g., Cygwin including g++ and make)
  • Create New C++ Project
  • In C/C++ Build > Settings > Other Flags Box, append "-std=c++11"
The following is the screenshot of my Eclipse 


Note: RAND_MAX is a macro defined in <cstdlib>. RAND_MAX = 32,767 in VC++, while RAND_MAX = 2,147,483,647 in GNU g++.

C++ 11 New Feature List (for Quants)

This is a list of C++ 11 (https://isocpp.org/wiki/faq/cpp11) new features (relative to C++98):
  • RValue Reference and move ctor.
  • Lambda Expression (for functional programming)
  • Concurrency API (future, async)
  • New Smart Pointers (unique_ptr, shared_ptr in <memory>)
  • Fixed-length <array>
  • <random> supports Mersenne Twister(MT19937) PRNG and distributions.
  • Enhanced Containers: <forward_list> and hashed <unordered_map>
  • Compile-time static_assert with <type_traits> for template code
  • noexcept, unexpected() and the enhanced <exception>
  • <regex> with EMCAScript syntax and backreference
  • RTTI: auto, decltype, and typeid 
  • Misc (ranged for loop, nullptr, non-type template parameters)

C++ Standard Library(since C++98), which is based on STL (designed and developed by Alexander Stepanov and Meng Lee), contains key components called containers, algorithms, functional and iterators.

Here the discussion is focused on Iterator, since it is very relevant to the performance. As shown in the following graph, C++/STL has 5-category iterators. Another way to present the iterator hierarchical relationship is using UML class diagram, with Input/Output as the bases at the top and Random Access Iterator at the bottom. A rule of thumb for choosing the iterators is to pick the weakest iterator first to accommodate the most efficient algorithm.

For example,
Forward Iterator: std::replace()
Bidirectional Iterator: std::reverse()
Random Access Iterator: std::sort()

Just for fun, I collected some C++ and OOP buzzwords and put them in a table.

RAII
Resource Acquisition Is Initialization
CADR
CTOR Acquire, DTOR Release, scoped-based res mgmt
RTTI
RunTime Type Info
BSS
Block Started by Symbol. Memory Layout: Stack, [Free Memory], Heap, Initialized Data, BSS, Text.
vtable
Virtual function Table
STL
3-legged STooL: Algorithm, Iterator, Containers
Algorithms
Algorithms use iterators and containers
Iterator Types
Input/Output, Forward, Bidirectional, Random Access
Container Types
Sequential, Associative. <forward_list>, <unordered_map>
Smart Pointer
Various raw pointer wrappers in <memory>
Pragma once
Directives similar to Include Guard
ADL
Argument-dependent lookup, Koenig Lookup
Move Semantics
Most pervasive C++11 feature. Move CTOR,  Move Assignment Operator for perf. Perfect Forwarding?
Move CTOR
Move Constructor
Rvalue Reference
<utility>
Boost
Open Source Library, some added in C++11/14.
Empty Aggregate Initialization
Could be very tricky.
Non-type Template Parameters
Enhanced template.
Exception-Safety
Basic and Strong exception safety. noexcept, throw, try-catch, unexpected() in <exception>. logic_error, runtime_error in <stdexcept>
Thread-Safety
<thread>, <future>. async(), future.get(), timeout.
volatile for hardware access, std::atomic for MT.
<random>
RAND_MAX? Platform-indep? Various Probability Distributions.
assert vs static_assert
#define NDEBUG vs compile-time assert. <type_traits>
OOP Key Concepts
Encapsulation, Inheritance, Polymorphism
SOLID
Single-responsibility, Open for extension/Closed for modification, Liskov substitution, Interface segregation, Dependency inversion.
LLVM
Low Level Virtual Machine, Clang compiler
JIT vs AOT
Just-in-time(CPU cycle stealing) vs Ahead-of-time Compilation
SIMD
Single Instruction, Multiple Data -- Flynn's Taxonomy. Intel MMX, SSE, AVX. 64bit CPU has 16 GPRs.
Hi-C Lo-C
High Cohesion, Low Coupling
GoF
Gang of Four, author of “Design Patterns”
IoC
Inversion of Control. Dep. Inj. Implements IoC for resolving dependency. No need to create the object by yourself. Template Method is another IoC example.
Pimpl
(Opaque-pointer)
Pointer to IMPLementation, Compiler firewall idiom, Handle class, “Cheshire Cat”.
Forward Declaration
Reduce build time


"... as you learned more [C++11], you were surprised by the scope of the changes. auto declarations, range-based for loops, lambda expressions, and rvalue references change the face of C++, to say nothing of the new concurrency features. And then there are the idiomatic changes. NULL(0) and typedefs are out, nullptr and alias declarations are in. enums should now be scoped. Smart pointers are now preferable to built-in ones. Moving objects is normally better than copying them."
  -- 
Scott Meyers, in 
"Effective Modern C++" 2015.

Friday, December 25, 2015

Java Native Interface

JNI supports two way interaction between Java and other languages, such as C++, C, Assembly.


Here I describe how to use JNI for Java/C++ 2-way Calls:
 1) Create a Java Project with MyExample.java with native methods.
     run "javah -jni MyExample" to generate MyExample.h

 2) Create a C++ DLL Project with MyDLL.cpp(#include "MyExample.h")
     In Project Properties, add Additional Include Directories:
            C:\Java\jdk1.7.0_79\include\win32;C:\Java\jdk1.7.0_79\include

 3) In Java project, add MyDLL.dll to Native Library Location.
     In Java code, add System.loadLibrary("MyDLL");


Note: A common run-time error when using JNI is java.lang.UnsatisfiedLinkError, which may be caused by 32-bit/64-bit DLL version mismatch or function signature mismatch. Here is a few tips to deal with this issue.
  • 64-bit JDKs usually work with 64-bit DLLs, while 32-bit JDKs work with 32-bit DLLs.
    Although java provides options -d32 or -d64, it's not always working.
  • To check if a DLL is a 32-bit, run "vcvarsall.bat amd64" and
    "dumpbin.exe \headers MyDLL.dll" 
  • One code base can support both 32-bit and 64-bit platforms.
The tools used in the above discussion: Java 1.7+, Eclipse(Mars) for Java, VC++(2013) for C++.

For best practice of using JNI, I recommend one article on IBM website: "Techniques and tools for averting the 10 most common JNI programming mistakes".

Note: Java is newer than C++, but they are influencing each other since the beginning. Wikipedia provides an excellent comparison of the big two, here is the link.

Thursday, December 24, 2015

QuantLib

1, QuantLib can be built with VC++ 2013, as instructed at http://quantlib.org/install/vc10.shtml

2, QuantLib is a well-designed C++ library and ported to R and Python.
    Check out the training material at http://www.implementingquantlib.com/p/training.html

3, Serious about QuantLib? Get a copy of <<Implementing QuantLib>> written by Luigi Ballabio.

4, Quick view of Class Hierarchy: http://yetanotherquant.de/QuantLib/book/BookQuantLib.pdf





Monday, December 21, 2015

Fun with Linux

1) Remove ^M
    $vi file.txt
    >:%s/^V^M//g

2) 64 bit or 32 bit?
    $uname -a
    $lscpu
    $more /proc/cpuinfo
    $nproc

3) Copy and preserving the same mode including timestamp
    $cp -p a.txt b.txt
    $cp -a a b

4) Who logged, from where?
    $w
    $last myuserid

5) Compiling C++ code?
    $g++ -shared ...
    $g++ -static-libgcc -L. -o hello hello.cpp
    $ar mylib.a mylib.o

6) Sort in reverse order (find, grep,...)
    $sort -r file.txt

7) To show free, total, and swap memory info in bytes
    $free -t

8) List top processes?
    $top -u myuserid

9) Backup or transfer files?
    $tar cvf a.tar /subdir
    $tar xvf a.tar

10) List all open files?
    $lsof -u myuserid

Sunday, December 13, 2015

Month-End Time Series vs Monthly Candle Chart

library(quantmod)
getSymbols("WMT")
wmt = do.call(rbind, lapply(split(WMT, "months"), last))

chartSeries(to.monthly(WMT), 
            major.ticks='months',
            subset='last 10 years')
addBBands()



Thursday, December 10, 2015

Random Walk in R

M = 150
N = 360

m = matrix(0,nrow=M,ncol=N)
m1 = apply(m, c(1,2), function(x) rnorm(1)) #runif, rnorm
m2 = apply(m1, 1, cumsum)
m2 = t(m2)

hist(m2[,N], 30)

a = mean(m2[,N])
s = sd(m2[,N])^2

sd2 = apply(m2, 1, sd)
matplot(t(m2), type="l")