Java, C + +, Python performance comparison (collation)

Source: Internet
Author: User
Tags numba

  

Links: https://www.zhihu.com/question/40393531/answer/133242263
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Someone wrote the code in Python as follows:
#-*-coding:utf-8-*-ImportTimeDefIsPrime(I):ForTestInchXrange(2,I):IfI%Test==0:ReturnFalseReturnTrueIf__name__==' __main__ ':T1=Time.Clock()N_loops=50000N_primes=0Fori in xrange (0 , n_loops): if isprime ( i): n_primes += 1 t2 = time. Clock () print str (n_primes) print  "run Time:%f S"  %  (t2 -t1)      
Accelerated code based on Numba
#-*-coding:utf-8-*-ImportTimeFromNumbaImportJit@jitDefIsPrime(I):ForTestInchXrange(2,I):IfI%Test==0:ReturnFalseReturnTrue@jitDefTp():N_loops=50000N_primes=0ForIInchXrange(0,N_loops):IfIsPrime(I):N_primes+=1Returnn_primesif __name__ ==  ' __main__ ' : t1 = time. Clock () n_primes = tp () t2 = time. Clock () print str (n_primes) print  "run Time:%f S"  %  (t2 -t1)      
(Insert some knowledge here: Interpreter and compiler, and Python interpreter)

I use Python execution time 23 seconds, with PyPy execution time 1.54 seconds, with Numba acceleration for 1.5 seconds, C language on the native MacOS execution time 1.3 seconds, Java running speed 1.45 seconds (Jre8), detailed see the picture, can be seen in the introduction of JIT compiled, performance in the C language , and writing Python is much easier than writing C, and it's also very important to write code faster than Java. For historical reasons, many of the C-language libraries used in Python libraries, such as pandas (pandas's matrix calculations with NumPy optimizations that are faster than handwritten C-language loops), can be designed to decouple the C-accelerated Python code and pure Python, Using different acceleration methods, such as Numba, can speed up a function individually, placing a large number of computations on a function with Numba acceleration (Numbapro supports graphics acceleration but commercial edition).

So just design it properly, Python has these solutions under the general computing problem. Performance is not a problem, but you can also use boost::p Ython to write a C + + call library to solve performance problems.

The following test shows that for performance, native Python is slower, in Windows Python is faster than Linux,macos, with pypy equivalent to java,c# speed, pypy,c# under Windows to benefit MSVC performance faster, Go language speed performance is relatively stable, C language theory is the fastest, but by the environment and the compiler has a large impact. The C#,java may be unstable during GC garbage collection because there is a large number of calculations in OOP that might be used to reclaim garbage-memory objects, which is no use of OOP, but is purely computational, and is theoretically the fastest in C + + languages.

Python and Java are slower than Java, Java is more powerful than the powerful JRE that improves n times, but Python can invoke many out-of-the-box open source libraries in many fields, with the advantage of data analysis, Pyhton's code is simpler than Java, easy to get started and use. With the help of the optimized computing library, the actual problem of NumPy Numba,pandas,scikit-learn,python is not lower than that of Java. Java is mainly the framework of too many, relatively complex, Java is mainly used for business process development, in line with the software engineering theory, scalability, strong type is conducive to the static examination of the program analysis. Java with the rise of Android, Hadoop,spark, a lot of companies to join the Java language, performance can also be optimized to solve a lot of problems. Many servers, such as Ubuntu Server,centos, support Python by default, while Java Virtual machines require installation configuration, and Python installation is relatively straightforward. Python Library has out-of-the-box sense, many business areas, you may still be using OOP to write code, considering design patterns, digging trenches with a hoe, and Python call excavator API has been cooking finished dinner, the disadvantage is that fuel consumption is relatively large.

Compared to C #, C # relies on powerful Microsoft-optimized. NET virtual machines and powerful vs Ides, which run faster than Java on Windows platforms, but after running across platforms such as Mono, the speed is slow and not fully functional. C # 's cross-platform capability is less complex than python,c# python, C # syntax and java,c++ borrowing, compared to programmers ' preferences. The advent of Mono, Unity3d in C # call C + + to do game business logic, can be run smoothly on the phone, embodies a lot of program performance is good design, can be high-performance in C/C + + write, with C#,java,python write easy to change business logic part. C # in Mon virtual machine running speed can also, but Linux control on the server has java,python,php, so with mono to do the web relatively small, from the success of Unity3d, C # as a business scripting language, using C + + to do the library can also get high performance. This is a solution to the contradiction between compromise performance and development speed. A lot of complex business language with java,c#, in the team development of good usability, also shows that the engineering of Python is poor, strong type of support is not suitable for static analysis, but Python one but with strong type declaration, then is another Java, is not a shortcut language. In the simple calculation comparison, each virtual machine language is not much different, in fact, in addition to the modern many business system bottlenecks in the IO, in the network, in the algorithm, in the design, You run 120 million times in 2 seconds, and no database or cache can do 2 seconds to record 120 million data, are 1 seconds below the 1 million record, if the network speed is slower, the average 1 seconds can record the next hundreds of thousands of data sky, so these languages have been waiting for IO to complete the task.

Compared with the go language, the go language is relatively new, the Go Language library is not rich in Python, after all, Python has developed for decades, the biggest advantage of the go language is the co-process, fast, support high concurrency, but any support for high concurrency of language programming is not an easy thing, the biggest disadvantage is that The name is Google go, and all the other giant companies have resisted the notion of a similar trademark in the sense of competition. Python is open source and uses a lot of companies. The grammar of the go language may develop better if it is similar to C#,java. Many languages why use it, not in grammar, not in performance, mainly in the language developed what successful products, others will mock this product, in this language, Docker is the go language development, suitable for large-scale distribution of containers.

Python is faster than C/C + + in Python, because C + + has pointers, and before you do, you need to think about pointers, pointers are bad, memory leaks, a bit of memory leaks don't matter, but multiplying the time multiplier will drain the entire memory. 24H*365 Day servers due to memory leaks cause real economic losses due to a restart, so it is best to use a pointer-free Java,php,python to develop a business background business program. But for the user to develop the same function of the program, the user will choose C + +, so in the software industry, countless successful sign software is C-python,java,c#,c/c++, this is the maturity of C + +. C + + is mainly the development cost is high, the same program may python,c# a week, C + + two months is normal. But in order to benefit, spend more time is also someone to do, as now someone with sinks to write encryption code, using FPGA to make the program chip, the pursuit of the ultimate speed. C + + Fast is compiled directly into binary, no JIT,VM, and Python is only the fastest extension to call C. Development costs are also very high cost, advanced C + + programs are expensive, such as in the United States advanced C + + programmers annual salary of more than million yuan, sometimes not big application, in easy-to-use language, on the advanced point of the computer, on the cluster on it. If you use a Python graphics card to speed up, buy a video card is million yuan. C + + is suitable for fine carving, take the elite route, Python suitable for rapid development, take the public line, in fact, for the impact of the performance of the part can be used in conjunction with Python to call A/C + + library. With the progress of compiling technology, computing power cost will decrease with time, computing power is more and more powerful, the most recent CPU multi-core frequency up to 5g, theoretically more than 2.5g CPU calculation speed, with liquid nitrogen overclocking up to 6.7g, the same nucleus is 1.5 times times faster than my computer (if using advanced C + + Language programmers optimized 1 time times the time spent 1 people/year, apparently more than the money to change the computer, the graphics card in the multi-core support floating point computing capacity is also getting higher (available Numbapro,pycuda), HPC in the cloud market can be rented, supercomputers can also be rented to the organization to test, Dynamic language with its ease-of-use development cost is low in many areas can replace high-performance compiler language, but the ultimate compiler performance software market is also expanding, many industries are not able to keep up with, many np-hard problems on the calculation of the demand is not linear increase can be met, the need for performance is actually more and more high, such as world competition for supercomputers, Bitcoin miners, deep learning algorithms. No one can take the place of anyone, but everyone has developed together. In what language there is no good or bad points, the key is in the target program is what to pursue.
Links: https://www.zhihu.com/question/40393531/answer/133242263
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

In fact, I think the best X language in my mind is
Java's cross-platform +c# IDE and syntax +python the performance +go language of the library +c++ language

Python in MacOS execution time 23.3 seconds, pypy in MacOS execution time 1.54 seconds, Python under Ubuntu test for 13.5 seconds, pypy under Ubuntu test for 2.3 seconds.

Speed up your MacOS results with Numba for 1.5 seconds.
Python runs at Windows7 for 7.4 seconds and PyPy under Windows7 for 0.6 seconds.

The result of running under Win7 with different Python compilers, PyPy is 0.56 seconds, Jython is 4.7 seconds, IronPython is 5.2 seconds, Python is 6.5 seconds

C language in MacOS running results 1.34 seconds (LLVM)
C language (VC++13) run time in Windows7 for 0.34 seconds, why so quickly, and the MSVC compiler may be related to the Windows Platform for Digital computing optimization. Including Python under Windows above, using the MSV to compile the version faster than MacOS. C language I use to play-o2 optimization under Ubuntu, with GCC is 2 seconds, with Clang is 1.88 seconds.
C Language Open-o2 Two-level optimization, with LLVM and GCC, the speed is almost 1.2 seconds, clang to hurry

Java in MacOS Run results for 1.4 seconds, I tested on Ubuntu for 2 seconds.

Java execution time under Windows7 is 1.23 seconds
The Go Language test code is as follows:
PackageMainImport("FMT""Time")FuncMain(){N_loops:=50000N_primes:=0T1:=Time.Now()Get current timeForI:=0;I<N_loops;I++{IfIsPrime(I){N_primes++}}T2:=Time.Since(T1)Fmt.Println("Time taken=",T2)Fmt.Println("Primes found",n_primes); } func isprime (i int) (bool) {for test := 2test < itest++{if i % Span class= "NX" >test == 0 {return false } } return true                /span>                
Go language in MacOS Test results 1.1 seconds, I tested in Ubuntu for 0.91 seconds

Go language in the Windows 7 platform for 1.18 seconds, you can also use grumpy, Python first into the go language, and then compile the go language into the binary implementation of the acceleration.

C # is based on mono in MacOS execution time 2.84 seconds, tested on Ubuntu for 1.8 seconds.

C # based on Windows7 Execution time 1.17 sec

The C # code is as follows:
UsingSystem;NamespaceTestprime{ClassMainClass{PrivateStaticLongLoopcount=0L;PrivateStaticboolIsPrime(LongI){For(LongTest=2;Test<I;Test++){If(I%Test==0){ReturnFalse;}Loopcount++;}ReturnTrue;}PublicStaticvoidMain(String[]Args){TimeSpanStart_time=Datetime.Now.TimeOfDay;LongN_loops=50000;LongN_primes=0;For(LongI=0;I<N_loops;I++){If(IsPrime(I)){N_primes++;}}TimeSpanEnd_time=Datetime.now. TimeOfDay -start_time; Console. Writeline (n_primes +  "primes found" ); console. Writeline ( "time taken =" + end_time totalseconds); console. Writeline ( "Loopcount =" + loopcount ); }}}           /span>                

Java, C + +, Python and other performance comparison (collation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.