Saving a lot of energy with C++ in web programming

Right now, most webservers were programmed in Python, PHP, Java and ASP.net The reason why has historical reasons. The first scripting language for building web-service was Perl, which is bash-language under UNIX. Later, more advanced languages like Python and PHP were developed. They have object-oriented features and have a simplified syntax. Most web developers today see Python and PHP as a here to stay language, but in reality their choice makes no sense. From Python for example it is known, that the language is 20x times slower then a native compiled C++ application. If a webserver is driven by Python this a huge slowdown.

At the same time, web scripting language are not very powerful and produce a lot of programming errors. The better alternative is to replace them all with modern C++17. The CppCMS framework is one example. It provides a blog engine, a wiki system and a general web application framework. Their main difference to existing PHP frameworks is, that it is fast and was programmed in C++. That means, if somebody doesn’t like a compiled language which is run naively on hardware he will don’t like CppCMS. What would happen if the server in the Internet switch from past PHP scripts to modern C++ programs? A huge saving in energy cost is the result. That means, the power consumption of the CPU is lower, if the program they run is programmed more efficient. A second aspect is, that projects written in C++ have the tendency into a higher software quality which means less bugs, and less attacks from hackers.

Teaching C++ for webprogramming isn’t a technical problem. Writing a C++ application which is able to print HTML5 tags to the screen is easier then with PHP. The problem is, that most web developers are not familiar with C++. They belief that a webserver has to be programmed with a scripting language which runs in a virtual machine and which isn’t C/C++. Some of them belief, that a Java based webserver is a high-performance application. But they never have seen the power of C++.

Sometimes the argument is, that the advantage of C++ against PHP is only small. A performance improvement of factor 3 is not a reason to switch the entire application. But let us ask the question from the opposite direction: Why should somebody stay on PHP, if C++ is better? The main advantage of C++ is, that the language can used for any project: in the Web, on the desktop, for games and so on. In contrast to PHP which is a web-only language. Somebody who is able to write PHP code, isn’t able to program a jump’n’run game with SFML. C++ was designed as general purpose language, that mean it compiles under any operating system, can be used for any purpose, is the fastest language and can’t be replaced by any other language.

The historical reason why C++ was ignored by early web developers has to do, that the opinion was that C++ the language is complicated and they want to make things easier. But, which part of C++ is difficult to handle? C++ consists only of some statements like if-then, for loop and class. The reason why C++ projects become complicated has to do with the domain. For example, programming a web framework or a 3D game can become a demanding task. Switching the language from C++ to Python doesn’t make things easier, because Python has only the same keywords (if-then, for loop, class statement). The real problem is domain centric, and to overcome it some kind of better library, a version control system and a bugtracker are the answer.

Perhaps a small example, why C++ is a easy programming language. Suppose we want to write HTML tags into a file:

std::ofstream myfile;
myfile.open ("index.html");
myfile << "subject " << "predicate "<< "object\n";
myfile.close();

Is the syntax more complicated then with PHP? No, what the programmer has to do is open the file, write some text to it and close the file. The only challenge is, that this kind of programming (using C++ for output a HTML file) isn’t very common. Only few tutorials are describing it.

Advertisements

C++ as a teaching language in Robotics

Sometimes the term educational programming language is pejoratively used to express that this language isn’t suited well for practical usage. But before somebody can write his first application a preliminary prototype has to be created. The best language in doing so is C++. C++ isn’t a real programming language but it is a nice try for anybody who want’s to learn what programming is, especially in the domain of robotics. The advantage is, that the language itself is very easy to handle. Only a few keywords are available:

• if then
• for loops
• classes, methods
• datatypes like std::string, std::vector, int, float

After a short introduction the students can write their first application in C++. The most interesting feature in C++ are external libraries. There are a lot available for example for threading, graphics output, GUI development, XML parsing and file output. In contrast to other teaching programming language like Forth the advantage is, that the performance is very fast. There is no interpreter, instead a compiler will transform the sourcecode into binary code. The result is, that cpu-intensive tasks like 3D rendering can be mastered on normal computers. The most interesting aspect of C++ is perhaps the pointer arithmetic. The student is able to make first steps in understanding this programming concept. And if had understood what pointers are, he can use this knowledge in any other programming language.

C++ has also a disadvantage. It is not the first choice in programming real application for a productive system. Here are languages like Python and Lisp better suited. They provide a superior security concept because of the usage of a virtual machine which isn’t available for C++.

Why C?

If we are looking around which programming languages are existing today, many so called new languages haven been invented. For example Python, Rust, Ruby, Java and others. All of them are started from scratch with the idea to make things easier and allows writing of large software projects. According to Stackoverflow and the number of available books, all of these language were a success. The tag “rust” has 10000 questions right now, Ruby was discussed 200000 times and Java is attractive for million of users. But from a technical point of view, we must ask if these language makes sense. Are they are better then C? The answer is simple: no, they don’t. C is the only high programming language available, the problem is that the Stackoverflow community isn’t able to see it. According to the facts, the tag “c” exists 282000 times in the online portal. That means, according to the numbers it is a minor language which was replaced a long time ago. The problem is, that Stackoverflow is wrong. Because in reality, over 90% of the program code was written in C. That means, Stackoverflow and the book market doesn’t reflect the reality but some kind of education experience. It is right, the Java is the number one language in the university context. As a result, many programmer have to do with exercises in that language. They are not asking stackoverflow because they want learn Java, they are posting questions because they want to improve their score.

From a technical perspective it makes no sense to waste ones time with a different language like C. Learning C is complicated enough and finding good literature too. If somebody argues, that not C but a different kind of programming paradigm is useful, he has simply no idea about programming. Because this is the reason why non-c advocates have so much impact? The people don’t want to learn programming they want learn something else. To stay in their community of non- programmers. That means, all the Java experts are forming some kind of Anti-c movement. Their shared identity is to reject the most important language out there.

But perhaps I’m wrong, perhaps C is outdated … Let us take a look into the history of C and why it was invented. The idea from the beginning was to write operating systems, libraries and internet networking code in C. What are today’s software engineering needs? Mainly the aim is the same. Existing operating systems and libraries have to improved, and no alternative to C was invented. Some years ago, Google invented the Go language as a C replacement, but according to the impact on real project, Go was not a success. And even somebody is using it, he will recognize that the programming style is very similar to c. Except the case that somebody is interested in functional programming he is with C well suited.

The question is not how to replace C, that question is how to teach C and how to write a tutorial about the language. I want to give an example for the problem. The combination of gtkmm, C++ and glade is a powerful combination of writing GUI applications which will run in Windows and Linux. The resulting binary file runs very fast and has a low memory impact. Such an application can be called superior to any other programming techniques available today. The only problem is: no books, no podcast and no stackoverflow post are explaining the details. That means, the technology is there, but no community is available which is familiar with it. I do not think, that we need something superior to C, we need only better blogs, podcasts, tutorials and programming courses.

According to stackoverflow, Glade and gtkmm are not relevant for the programmers. Only 500 questions are tagged with that name and in most of them, heavy problems are discussed. Is Glade and gtkmm wrong? Is it difficult to program a GUI application with it? No, the technology is right and it works great. The problem is, that the programmers are not familiar with it. Instead, the stackoverflow community is discussing endless about the question how to paint with Java a gui window on the screen.

Python vs. C

Suppose someone decides to ignore the c programming language and prefers something which has no pointers, is high-level and interpreted. They he would probably decide to give Python a chance. Python is even more high-level then Java and it solves all problem which makes C complicated. So from the perspective of a beginner, Python is an ideal alternative to C. But what exactly is the benefit? Are Python programs easier to write, easier to read and easier to maintain then C counterparts?

Answering this question is easy, we can take a look at rosettacode in which all programming tasks are solved in the C and also the python syntax. The problem is, that there is no real advantage in Python. I would guess, that from the syntax level both langauges are the same. The reason is, that is they working with the procedural principle. That means the programmer has to define functions, give them parameters and this results into a program. If someone isn’t able to program something in C he will fail with Python too.

And this is the problem. Python doesn’t offer a real benefit. According to the definition it is high-level and pointer free but in reality, it makes programming harder. The fastest way in writing sourcecode is not to write any line of code and simply use the package manager of the operating system to search for existing software. And if the package manager only gives results back written in Python, the user will have a serious problem. Only if software isn’t available it makes sense to write them from scratch. And if the programmers has to figuring out a problem in detail, implement the algorithm and testing the sourcecode, he can take the normal C language, because it compiles into fast machine code.

To understand Python we must go back in the history. Before Python, the bash scripting languages were very limited. A normal bash script can have maximum 100 lines of code, and also perl wasn’t made for huge programming projects. Python is some kind of improved perl. From a technical perspective it makes it possible to write very complex bash-scripts, including object oriented features, 2000 lines of code and even output in HTML for browser interaction. At the first look this is great, and many beginners used Python for implementing frameworks. The problems came later. After a while the Python sourcecode becomes instable. Using a scripting language for writing large frameworks and libraries is a bad idea. Python supports this programming technique and motivates people to write software like they are developing bash scripts. The result is non working software and a lots of extra work.

Python can be called the worst language ever invented. It pushes the programmers into the wrong direction. Instead of teaching them how to use normal C/C++ for writing applications, they are learning Python and think, they are programmers. If Python would increase the programming productivity in numbers of lines per day, i wouldn’t argue against it. But the the truth is, that with C++ the programmers are creating 10 lines of code and with Python the same amount. The reason is, that testing a software and inventing an algorithm is the same in both languages.

How to manage pointer complexity in C++

Pointers are the source of most confusion in C++ and the reason why many Python, Java and PHP programmers stay away from that language. What pointers are on a technical level can be read in many books, but how has the C++ community managed the problem of understanding pointers? The first idea might be to explain pointers as obsolete and invent a programming which doesn’t need them. The C++ community has decided against this idea because pointers are not only part of C/C++ but also part of x86 assembly language. Yes, it is true, any assembly language dialect like X86, 6502 or ARM has pointers too. In each of the registers it is possible to store a value but also a memory address, and because of this reasons, pointers are used by C/C++ too.

The hopeful message for beginners is, that no one of the programmers has understood pointers in depth. But there is a huge amount of books and online Q&A forums like Stackoverflow how are familiar with any detail. That means, any question about pointer arithmetic has a correct answer, and someone in the community is an expert for this detail problem. The knowledge about pointers is distributed along the community and at the end it makes sense.

In other programming languages like Python on the first look no pointer problems are there. Everybody is happy. The problem is, that more difficult programs can’t be written without pointers. Complex algorithm for image manipulation need them and lowlevel operating system drivers too. That means, in all these domains Python is wrong language and even if somebody has read some books and asked the expert for help, he isn’t able to realize his idea. That is perhaps the most prominent difference to C++. In the C++ community it makes sense to ask for help, and at the end of the day somebody knows the details. That means, the language itself has no limit and it is possible to do anything with it. How much the beginner needs pointers depends on his projects. In the newest C++17 standard, a newbie can write many lines of code, without ever need pointers. He can define classes and methods, send them messages with the variables itself and has no need for referencing. In more complex problems like library programming, he will probably need them early and will recognize them as a powerful tool to save memory and cpu ressources. The reason why modern mp3 codecs need so less ressources has to do with pointers.

Dialog based learning

How does C++ experts handling pointers in reality? What though model they use to determine which of the following commands is right: int a, int *a, &a? Instead of a common misconception they are not thinking like a machine or like a C++ compiler. Instead they are imagine what somebody of the community will think about it. Either they are posting a direct question to stackoverflow or they imagine what would happen if they are doing so. The last one (only imagine what the community will think about it) is widespread used by experts. They know, how pointer experts will argue about it, and they adapt the commands to obey this argumentation.

That means, C++ programmers are coding along an imaginary code of conduct which is given by expert programmers who have written real programs. C++ programmers are not using itself, instead they are taking programming patterns used by Microsoft, Borland, or other higher authorities they trust. They reason is, because pointers itself are useless, and the only reason they are finding a way into the sourcecode is because of certain problems they solve.

Tribute to the C/C++ language

To understand C/C++ better, we must search for a potential alternative. The world outside of C/C++ consists of Python, Java, C#, Ada, Pascal and many other languages. All of them have a large fan base, a well documented in the literature and many thousands projects were made in these languages. But why exactly is C/C++ superior? Answering the question can only be done in a concrete software project. Suppose we want to write a new operating system, because we don’t like the existing one. And of course we know it better and made everything right from the beginning. But which is the right language to write an operating system, if we don’t want to use C/C++? The natural choice is the assembly language, because this is the fastest language available and is understood by the microprocessor. Writing an operating system in assembly is what the programmers done in the 1960s and early 1970s. The advantage is, that apart from an assembler we need no other software packages like a compiler and can start with the project. The disadvantage is, that programming in assembly takes a long time.

Suppose we don’t want to program in Assembly but in a higher language. Then we need a compiler for converting the sourcecode to Assembly. All of the programming languages invented in the past can be called either an compiler or an interpreter. They are taking sourceocode in Python, Java and Ada and converts is to lowlevel assembly language. And here is the point in which we can compare C/C++ with other languages. We will notice, that the compilers for Python or Java are not very advanced. That means, the assembly output didn’t fulfill the needs. Only a C/C++ compiler can produce powerful and fast assembly code.

Sometimes the Rust programming language is discussed as a potential alternative to C. Rust was developed recently and has the goal to avoid some pitfalls of C. But, if we are take a look into the rust specification, we will notice, that Rust also knows smart pointers and raw pointers. And that the sourcecode which is using such pointers looks very similar to C. That means, Rust can be called a c dialect not a new programming language. It will make the things not easier.

The problem is, that any programming language has to be converted into machine languages. Either by a compiler or at runtime by an interpreter. Pointers in C are complicated not because of C itself, but because pointers in Assembly language are complicated. Avoiding them isn’t possible, any assembly programs has pointers. They are a fundamental building block.

Let us take a critical look in modern operating systems. What are potential things we can make better? Some programmers have decided to program their own operating system from scratch. A good example is the “thor-os” project which is hosted on github, was written in c++ and contains 5400 lines of code. The screenshot looks unix-like. It is a modern operating system, but it isn’t a replacement for existing one. The limit is not the programming language, the bottleneck is the number of codelines. 5400 lines of code isn’t very much, to make the os better, more lines of code has to be written. But writing code is complicated and takes time. So we can say, that not technical problems, but social aspects are the reason why Thor-os has stopped the development in 2014. The programmer had simply not enough resources to program more sourcecode and he knows, that the result will not better then the existing Linux kernel.

To summarize the situation a bit: if today’s LInux kernel is written in Assembly it would be possible to reinvent the wheel because it is easier to use C then Assembly. But since the mid 1970s all UNIX clones are written in C, that is from a technical perspective the optimum. How good an operating system will be depends no longer on the programming language, but on social conditions, that means how many programmers are involved in the project. Instead of comparing an operating system written in Java with an operating system written in C the better approach is to compare 10k lines of code with 1 million lines of code. The programming language C has no real alternative, the only criteria is the lines of code metrics.

Bug: SDL2 needs to much CPU ressources

SFML with C++ isn’t the fastest library on earth. Can we tune the performance by switching to lowlevel SDL2 commands? The following hello world sourcecode outputs with SDL2 under Fedora Linux a simple line with a framerate of 120 (which is very fast and enough for computergames).

// g++ main.cpp -lSDL2
#include <iostream>
#include "SDL2/SDL.h"
int main()
{ 
  SDL_Window* window = NULL;
  SDL_Renderer* renderer = NULL;
  SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer);
  int fps=120;
  
  for (auto i=0;i<100000;i++) {
    if (i%fps==0) std::cout<<i<<"\n";
    bool quit = false;
    SDL_Event event;
    SDL_Delay(1000/fps);
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) 
        quit=true;
    }
    if (quit==true) break;
    // drawing
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer); // fill the screen with background color
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderDrawLine(renderer, 20, 20, 150, 170);
    SDL_RenderPresent(renderer); // update screen
  }

  // cleanup SDL
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();
}

C++

After compiling and executing the program the SDL2 window is shown on the screen. But a detail look into the amount of CPU ressources which was occupied shows us, that SDL2 needs exact the same ressources like SFML before. The application itself eats 7.3% of the overall CPU, plus the general display manager “gnome-shell” is additional loaded with around 20%. That is too much, because apart from one single line no advanced objects or sprites were used.

Using libraries without pointers in C++

Many developer are preferring Java and C# over C++ because the pointer syntax of Stroustrup’s language is a bit complicated to handle. Let us first take a look into a “with-pointer” example to draw with the FLTK framework a gui window on the screen. According to the official documentation the sourcecode is:

// FLTK gui test, g++ fltk.cpp -lfltk
#include <iostream>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>

int main() {
  Fl_Window* win = new Fl_Window(100,100,100,100,"Title");
  win->show();
  return Fl::run();
}

If the fltk-devel library was installed on the local Windows or Linux machine the program will compile into a 12kb executable file which shows a hello world window. So far so nice. The only problem here are the pointers. It is not a smart pointer like in modern C++ versions, it is the old type. The surprising thing is, that it is not the fault of C++ itself, but of the documentation. It is possible to write the same program in a modern style without explicit pointers:

// FLTK Uniform initialization
// g++ -std=c++14 fltk.cpp -lfltk
#include <iostream>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>

int main() {
  Fl_Window win{100,100,100,100,"Title"};
  win.show();
  return Fl::run();
}

The syntax with the Curly brackets is called uniform initialization and looks more modern. Source: https://stackoverflow.com/questions/51377399/why-are-some-libraries-provide-a-pointer-free-access-and-others-not