问题
I translated a Java program into C++, and I was getting very slow performance from C++ as compared to Java. Looking at the activity monitor, I saw that the Java program, which I ran first, was using over 90% of the CPU, while the C++ program was using around 30%.
It appears that the JVM is able to harness the full power of the CPU without user intervention. What changes should I make to use the CPU better for the C++ case?
回答1:
Read a good C++ programming book then see this C++ reference. Read also the documentation of your C++ compiler (perhaps GCC).
Read also some operating system textbook.
Consider using frameworks such as POCO or Qt or Wt.
With a multi-core processor, you might use C++ threads. You'll need to synchronize them, e.g. using mutex and condition variables.
On GNU Linux, you could read advanced linux programming and use the syscalls(2) related to process creation and management (e..g. fork(2), execve(2), waitpid(2)...) and profiling (see time(7), profil(3), gprof(1), perf(1)).
On Windows, you need to use the WinAPI.
I translated a Java program into C++
In general, that is a bad idea. Learn your programming language and your operating system, and design your software for it.
Take inspiration from existing open source software on github or gitlab (e.g. RefPerSys, Firefox, Tensorflow, OpenJDK, Clang static analyzer, Fish ...)
Java implementations (e.g. JVMs) have some garbage collection and some class loader.
C++ implementations do not have any garbage collection. So read the GC handbook. Notice that circular references are hard to handle efficiently in C++, and this could explain your performance issues.
On Linux/x86-64, you might load plugins with dlopen(3) with dlsym(3) (or generate machine code at runtime using asmjit or libgccjit)
来源:https://stackoverflow.com/questions/65129452/how-to-utilise-all-cores-for-c-program