TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: Is C/C++ really faster than Python?

36 点作者 sunilkumarc将近 10 年前
I have seen many people saying they choose C&#x2F;C++ over Python during programming challenges because the performance of Python is lesser compared to C&#x2F;C++. How correct is this fact?<p>If Python is actually slower compared to C&#x2F;C++, how much slower is it when we implement the same algorithm in C&#x2F;C++?<p>Is it really necessary to use only C&#x2F;C++ and not Python when solving some questions which involve a lot of computation?

19 条评论

overgard将近 10 年前
Yes. It&#x27;s much faster. The reason C++ is fast is because you have explicit control over allocations and it compiles to native code (among other reasons). There are also a lot of subtle things that you can control in C++ that you can&#x27;t in python, like memory layout. Memory layout is extremely important for CPU cache, and CPU cache is extremely important for performance. (Reading data from RAM is generally orders of a magnitude slower than reading from an L1 or L2 cache. For some reason this never gets mentioned in university CS courses, but there are a lot of data structures that are &quot;theoretically&quot; fast for certain things but in practice very unfriendly to hardware. For instance, linked lists. Sure insert&#x2F;delete is O(1), but since linked lists are quite possibly the least cache friendly data structures in existence, you&#x27;re better off with a vector&#x2F;array even if you&#x27;re inserting all the time. I&#x27;m not just making this up, you can read talks by people like Bjarne Stroustroup on this topic)<p>As to whether it matters for the algorithm, it depends on the algorithm. It&#x27;s almost always going to be much faster in C, but, how fast do you really need it to be? Python is very good at saving programmer time, so if performance is not particularly important, I just wouldn&#x27;t worry about it.
评论 #9753658 未加载
评论 #9753706 未加载
评论 #9753746 未加载
评论 #9753724 未加载
dekhn将近 10 年前
It&#x27;s basically 100% true. Any program written in python can be translated to an equivalently functioning C++ program which requires fewer expensive operations to run.<p>The Python VM is doing a fair bit more work per instruction it executes; for example, incrementing an int isn&#x27;t going to be a simple register add, it&#x27;s going to involve a pointer dereference, some comparisons and branches, execution of several C functions, and overhead for interpreting the VM bytecode.<p>That said, if you understand what Python is doing under the hood you can greatly speed up your programs and approach C++ performance in some areas.<p>That said, I strongly recommend all performance-sensitive code is written in C++ with wrappers to drive it from Python.
评论 #9769709 未加载
dalke将近 10 年前
See &quot;The Computer Language Benchmarks Game&quot; at <a href="http:&#x2F;&#x2F;benchmarksgame.alioth.debian.org&#x2F;" rel="nofollow">http:&#x2F;&#x2F;benchmarksgame.alioth.debian.org&#x2F;</a> for a head-to-head comparison of various small programs as measured across a wide number of language implementations. Do be careful that a &quot;language&quot; has no performance, only implementations of the language. For example, different implementations of Python may differ by an order of magnitude on a given task, as might different C compilers. Java and Javascript used to be considered slow languages, but the effective billions of dollars of R&amp;D improved the implementations.<p>The overall solution space is complex. For example, development time on Python is about 1&#x2F;2 that of C++ (the classic paper is <a href="http:&#x2F;&#x2F;page.mi.fu-berlin.de&#x2F;prechelt&#x2F;Biblio&#x2F;jccpprt_computer2000.pdf" rel="nofollow">http:&#x2F;&#x2F;page.mi.fu-berlin.de&#x2F;prechelt&#x2F;Biblio&#x2F;jccpprt_computer...</a> - is there something more recent?). Since algorithms can trump raw performance, it may be that in 8 hours its possible to develop a more sophisticated implementation in Python which outperforms the naive implementation in C++.<p>In the late 1990s, when people started using Python for traditional supercomputing problems, the phrase was to use Python to &quot;steer&quot; the low-level code written in a faster language. For example, NumPy is a Python API which uses C&#x2F; Fortran&#x2F; assembly code at lower levels for doing array calculations. Thus, only some people need to be skilled in both levels, while most can focus on writing Python code. The actual code has parts written in multiple languages, and not &quot;only C&#x2F;C++&quot;.
评论 #9753513 未加载
评论 #9753554 未加载
评论 #9753871 未加载
vardump将近 10 年前
Programming languages aren&#x27;t slower or faster. The implementations of them are.<p>Provided no FFI or extensions written in other languages, non-I&#x2F;O bound interpreted CPython is 50-100x slower than C&#x2F;C++. JIT compiled (PyPy, etc.) Python might be in 2-10x slower bracket.<p>If extensions written in C&#x2F;C++ are used, then you might be effectively comparing those extensions against another C&#x2F;C++ implementation.<p>So <i>if</i> your code is going to be I&#x2F;O bound and&#x2F;or can effectively offload all computation in modules written in C&#x2F;C++ (like NumPy), then Python might be practically as fast as C&#x2F;C++.<p>If you use pure interpreted Python and implement compute limited algorithm in it, your code is going to be 50-100x slower than C&#x2F;C++.<p>Real life scenarios are probably somewhere in between those two extreme cases.
评论 #9753576 未加载
评论 #9753593 未加载
评论 #9753666 未加载
评论 #9753601 未加载
bane将近 10 年前
I find Python&#x27;s speed is <i>highly</i> uneven and dependent on what you are doing with it.<p>Are you doing something that has some kind of underlying C implementation (file I&#x2F;O usually)? Then it should be pretty quick.<p>Are you doing something that is all handled by the Python interpreter? Expect it to be slower than you&#x27;d like. e.g. for loops in Python are usually slower than list comprehensions.<p>It can be kind of frustration to write a bunch of code that runs lightning quick and then suddenly see your runtimes explode when you add a few more fairly trivial lines to complete off some code. I&#x27;d almost rather Python had a more consistent performance profile even if it was a bit slower on average than fastest possible, because it would make it easier to reason about the performance of your code.<p>So far I mainly just use the default Python implementation, but if you&#x27;re really struggling with it, it&#x27;s probably worth it to look into using one of the JIT or JVM implementations for more consistent speed profiles.<p>BTW, there&#x27;s also all sorts of weird performance tweaks in the community...mostly of the form of syntax A vs. syntax B, and I&#x27;ve found that surprisingly few of them are &quot;real&quot; or offer more than trivial speedups.<p>In other cases, in other languages, you <i>know</i> what you need to do to speed things up, but Python either doesn&#x27;t offer that mechanism in the language or buries it under somewhere else (try finding out how to preallocate lots of entries in a dictionary instead of incrementally growing it, it exists, but it&#x27;s almost impossible to find using search words like &quot;preallocate&quot;)
koonsolo将近 10 年前
If you consider the raw languages, C&#x2F;C++ is indeed faster. But unfortunately it&#x27;s not that easy.<p>It&#x27;s easier and faster to write a program in python that in C++. So given limited programmer time, it might be possible to write a faster solution in python than in C&#x2F;C++ because you have more time to optimize your algorithm instead of fighting with the compiler. If you have a big project, you can spend the extra programmer time you gain by using python by moving crucial code from python to C. The crucial code can be found by using a profiler. (Saw an article about this some time ago, but don&#x27;t remember which company actually did this)<p>Finally, python has a lot of math libraries that offer good speed for computation intensive operations, see <a href="http:&#x2F;&#x2F;www.scipy.org&#x2F;" rel="nofollow">http:&#x2F;&#x2F;www.scipy.org&#x2F;</a>.<p>So yes, it&#x27;s not that easy. I would suggest use Python because it programs easier&#x2F;faster, and if you really run into a wall, you can always port parts to C.
tehwalrus将近 10 年前
The same code is faster (and easier) to write, correctly, in Python than in either C or C++. (this depends a little on what you&#x27;re writing, but not much: C&#x2F;C++ make you specify much more about your code than python does.)<p>The same code, however, will run faster on C&#x2F;C++. This is because python is doing some of the work for you, and you did that work upfront when writing the C&#x2F;C++.<p>If you are doing something which involves a lot of computation, which all fits in RAM (using numpy in python will make that a fairer test between the two choices), then C&#x2F;C++ will be faster.<p>Remember that a good pattern is to write your high-level logic in Python, and write a python implementation of your app, and then profile it to work out the slow parts of the code and speed them up using Cython[1], which will allow you to convert python-like code to efficient C (you can also straight up borrow C&#x2F;C++ implementations from other people, too). This pattern is designed to balance minimising both programmer-time (since you will only have to code the important bits in C) and run time (since the performance-critical bits can be optimised.)<p>[1] <a href="http:&#x2F;&#x2F;cython.org&#x2F;" rel="nofollow">http:&#x2F;&#x2F;cython.org&#x2F;</a><p>(for pedants: I am referring to the CPython implementation, which is the only one which supports C&#x2F;C++ extensions.)
meir_yanovich将近 10 年前
Yes , and there is no point to ask questions like is X scripting is faster then c++ . each software that is running by software will be slower then native code .
aikah将近 10 年前
I wish people would stop saying &quot;C&#x2F;C++&quot; , these are 2 different languages.<p>Python* itself is written in C, not in Python. Which should give you clues to mediate and find your own answers.<p>*: Python, the canonical implementation.
评论 #9753696 未加载
评论 #9753631 未加载
koenigdavidmj将近 10 年前
CPython is built more naively for lots of operations. A global lookup is a dictionary lookup. Getting a symbol out of an object is a dictionary lookup. An object creation is always an allocation; variables don&#x27;t go on the stack. Everything is reference counted. The old &#x27;range&#x27; builtin would create an actual list of that length in memory, rather than just keep track of the start and end points like a C-style for loop.<p>Other implementations could theoretically do better. PyPy can detect after a while that a variable can safely be declared on the stack, and so it will start to do that. If the object type is known, then a field lookup becomes just adding an offset to the pointer. It can even use different implementations for the same Python-visible classes (to store a range result in constant space, but still appear to be the full list, or use a different type of dictionary for objects and {}, or other things like that).
mangeletti将近 10 年前
The &quot;Python is the language, not the implementation&quot; answer has already been given by @dalke, so I&#x27;ll answer whether cPython, the implementation of Python that Python developers commonly use, is slower than C&#x2F;C++:<p>cPython is necessarily slower and uses more memory than C for most tasks, and that&#x27;s because cPython is implemented in C. You couldn&#x27;t expect a new programming language that was implemented in Python to be faster than Python, either.<p>This is less of a concern for scientists and others with very tough performance requirements than it otherwise would be, in part, because cPython code can delegate C and C++ code[0]. This means portions of your program that need to be highly optimized can be implemented in C or C++, while the rest of your program can continue to be written in Python.<p>[0] <a href="https:&#x2F;&#x2F;docs.python.org&#x2F;3&#x2F;extending&#x2F;extending.html" rel="nofollow">https:&#x2F;&#x2F;docs.python.org&#x2F;3&#x2F;extending&#x2F;extending.html</a>
评论 #9753577 未加载
davidkhess将近 10 年前
My perspective having developed with Python for over 20 years now: it depends on the nature and context of the problem being solved.<p>In my experience, you usually need a CPU intensive problem for the implementation language to be a speed concern. Many practical everyday problems solved with Python (outside of contests and specialized fields) tend to be I&#x2F;O bound.<p>Secondly, even when you do have a CPU bound problem, many Python modules you might use to solve it are wrappers for C&#x2F;C++ implementations.<p>As a result, I&#x27;ve come to think of Python as a control and integration language and less as a platform for base algorithm implementation.<p>Viewed that way, I&#x27;ve found Python to be unbeatable for speed of implementation and long-term maintainability (two of my top metrics for valuing code).
Jdam将近 10 年前
I implemented an algorithm in Python and C++. Heavily IO bound task, read a float, multiply it with a factor, save to another file. Input file was several Gigabytes. I didn&#x27;t do any optimization and I&#x27;m a C++ noob. Python was 30 times slower.
fauigerzigerk将近 10 年前
It is generally true. For the same algorithm, C++ can be hundereds of times faster, but sometimes you can push computations down to the C code in which the most popular Python implementation is written.<p>A very general approach to optimizing Python code is to look at all your loops and ask yourself which ones you can replace with library calls.<p><a href="https:&#x2F;&#x2F;wiki.python.org&#x2F;moin&#x2F;PythonSpeed&#x2F;PerformanceTips" rel="nofollow">https:&#x2F;&#x2F;wiki.python.org&#x2F;moin&#x2F;PythonSpeed&#x2F;PerformanceTips</a>
Bootvis将近 10 年前
What would be a good book to start to learn high performance C++ code?
评论 #9753987 未加载
cia48621793将近 10 年前
What about PyPy? It generates native (JIT) code and run as fast as C.
评论 #9753617 未加载
评论 #9753637 未加载
uxcn将近 10 年前
It&#x27;s generally difficult to say one language is <i>faster</i> than another, but there are some significant differences between the languages and implementations of Python and C&#x2F;C++ that have very real performance implications.<p>Python is a dynamically typed language. This means that the language will handle conversions between types depending on the context. For example, one context can yield a 64 bit integer, another a arbitrary precision integer, another a string. Keeping track of when to use one versus another, and converting between costs performance. The different data representations for each type have different performance implications as well. For example, a 64 bit integer can fit into a register, and it&#x27;s generally only one cycle to perform any math on it. Arbitrary precision requires math and carry be performed for every digit in the value. With C++, types are explicit, which means there is only one type for a value, and the representation is generally the most efficient (eg 64 bit integer).<p>Python is also generally interpreted. This means that code can&#x27;t be directly executed on the CPU. An intermediate layer, called the interpreter takes an intermediate representation of the Python code, and translates it into instructions that run on the CPU. This happens at runtime, which adds overhead for each intermediate instruction. The more instructions you need to do something, the more overhead you have. C&#x2F;C++ is compiled directly into code that executes on the CPU which is typically faster. This also allows for higher levels of optimization in code, since there&#x27;s an understanding of what a piece of C&#x2F;C++ code will look like when it executes on the CPU. The compiler can also optimize the code further, since it knows the code (generally) won&#x27;t change. It&#x27;s also a lot easier to use native features of the CPU like stack allocation, which is drastically faster than heap allocation.<p>One of the other differences is that Python tends to provide higher levels of abstraction than C&#x2F;C++ code. So, doing something like a set intersection using <i>x.intersection(y)</i> may not necessarily be the fastest way. Python may do a hashed compare, but sorting and using <i>memcmp</i> may be faster. It&#x27;s a lot more code to write though. This is generally the tradeoff for Python vs. C&#x2F;C++ (natively compiled code) in general.<p>If you&#x27;re concerned with performance, but you like programming in Python, you may want to check out Haskell. It&#x27;s provides a lot of the same higher level abstractions Python provides, but the language is strongly typed and it can be compiled to native code. A simple example... <a href="http:&#x2F;&#x2F;uxcn.blogspot.com&#x2F;2011&#x2F;11&#x2F;algorithm-complexity.html" rel="nofollow">http:&#x2F;&#x2F;uxcn.blogspot.com&#x2F;2011&#x2F;11&#x2F;algorithm-complexity.html</a>.
评论 #9759449 未加载
yoklov将近 10 年前
Yes. Does it matter? It depends.<p>If you&#x27;re writing a game in python, you&#x27;re going to have a bad time. Yes, I know CCP does it, but from what I&#x27;ve heard their engine is C++, and even then it&#x27;s been a long, uphill battle. You&#x27;re just going to have a very hard time meeting soft-realtime performance constraints (e.g. 30ms or 15ms frames) if very much of your code is in python.<p>If you&#x27;re doing a programming challenge, you&#x27;ll probably be fine? I&#x27;ve never done a programming challenge, but my assumption is that getting a result is the goal, and the performance of the code that gets it isn&#x27;t that big of a deal, so long as it runs in a reasonable amount of time.<p>Really, the point is that you aren&#x27;t going to see algorithmic-level speed differences between C&#x2F;C++ and python most of the time. There are cases where this is untrue (e.g. where the algorithm relies on low level memory control), but it&#x27;s true enough. You&#x27;ll see a constant factor speedup, ranging somewhere between small and massive. I&#x27;ve heard 100x is typical for code that runs mostly in python and isn&#x27;t just calling out to C, C++, or Fortran.<p>That said, the 100x number could be way off. For compute intensive tasks, if you&#x27;re using numpy, you&#x27;ll see a much smaller speedup. If you&#x27;re not using numpy, but are great at writing multicore and simd code, you could see a 100<i>(num_vector_lanes)</i>(num_cores), so on a recent quad-core intel chip, you might be able to get a 100<i>8</i>4 = 3200x speedup. This would take a long time to write, only applies to problems that are both compute-bound and easily parallelizable, and could be overly optimistic, but you get the idea (I don&#x27;t know where the 100x number comes from, and how well the C++ programs it was compared with were written -- if it&#x27;s from Alioth, last I checked they tended to leave a lot of perf on the table, but are not too bad).<p>Also, cache friendliness can make a massive difference. I&#x27;ve seen 10x speedups in C++ programs by utilizing the cache better, and I&#x27;ve heard of people getting even more significant speedups. Python&#x27;s implementation is extremely cache unfriendly, <i>but</i> writing cache friendly C++ programs is non-obvious to a lot of programmers (or they don&#x27;t consider it, or something), so you might loose out here. Along these lines, if your memory allocation patterns in C++ are naive, your code won&#x27;t perform very well, and a lot of C++ programmers fall victim to this.<p>So who knows. If you&#x27;re great at C&#x2F;C++, know your architecture, are excellent at parallization and SIMD, and have the right problem, the difference could be massive. Barring that, I&#x27;d guess you&#x27;d get something like a 10x-50x speed up for average code, which is a lot, but maybe not that significant<p>Sort of rambled there, hope that made sense.<p>P.S. A lot of this is only true for CPython. I hear PyPy is faster (still no simd, multicore, or memory allocation or layout control though, so I suspect you can still beat it a lot of the time).
known将近 10 年前
If we load entire data into memory the difference is negligible.
评论 #9753668 未加载