Or is it now the other way around?
还是相反?
From what I've heard there are some areas in which C# proves to be faster than C++, but I've never had the guts to test it by myself.
据我所知,在某些领域,c#被证明比c++快,但我从来没有勇气自己测试它。
Thought any of you could explain these differences in detail or point me to the right place for information on this.
我想你们任何人都可以详细地解释这些差异或者给我指出一个合适的地方来了解这些差异。
27 个解决方案
#1
280
There is no strict reason why a bytecode based language like C# or Java that has a JIT cannot be as fast as C++ code. However C++ code used to be significantly faster for a long time, and also today still is in many cases. This is mainly due to the more advanced JIT optimizations being complicated to implement, and the really cool ones are only arriving just now.
基于字节码的语言(如c#或Java)具有JIT的速度不如c++代码快,这是没有严格原因的。然而,c++代码在很长一段时间内都是非常快的,而且在很多情况下仍然是如此。这主要是由于更高级的JIT优化变得复杂而难以实现,而真正酷的JIT现在才刚刚到达。
So C++ is faster, in many cases. But this is only part of the answer. The cases where C++ is actually faster, are highly optimized programs, where expert programmers thoroughly optimized the hell out of the code. This is not only very time consuming (and thus expensive), but also commonly leads to errors due to over-optimizations.
所以在很多情况下,c++更快。但这只是答案的一部分。c++实际上更快的例子是高度优化的程序,在这些例子中,专家程序员彻底优化了代码。这不仅非常耗时(因此也很昂贵),而且由于过度优化,通常还会导致错误。
On the other hand, code in interpreted languages gets faster in later versions of the runtime (.NET CLR or Java VM), without you doing anything. And there are a lot of useful optimizations JIT compilers can do that are simply impossible in languages with pointers. Also, some argue that garbage collection should generally be as fast or faster as manual memory management, and in many cases it is. You can generally implement and achieve all of this in C++ or C, but it's going to be much more complicated and error prone.
另一方面,解释性语言中的代码在运行时(运行时)的后续版本中变得更快。NET CLR或Java VM),没有您做任何事情。JIT编译器可以做很多有用的优化,它们在语言中是不可能有指针的。此外,一些人认为垃圾收集通常应该和手动内存管理一样快或更快,在很多情况下确实如此。一般来说,您可以在c++或C语言中实现并实现所有这些功能,但这将更加复杂,并且容易出错。
As Donald Knuth said, "premature optimization is the root of all evil". If you really know for sure that your application will mostly consist of very performance critical arithmetic, and that it will be the bottleneck, and it's certainly going to be faster in C++, and you're sure that C++ won't conflict with your other requirements, go for C++. In any other case, concentrate on first implementing your application correctly in whatever language suits you best, then find performance bottlenecks if it runs too slow, and then think about how to optimize the code. In the worst case, you might need to call out to C code through a foreign function interface, so you'll still have the ability to write critical parts in lower level language.
正如Donald Knuth所说,“过早优化是万恶之源”。如果您确信您的应用程序将主要由非常关键的性能算法组成,并且它将成为瓶颈,并且在c++中肯定会更快,并且您确信c++不会与您的其他需求冲突,那么就使用c++吧。在任何其他情况下,首先集中精力以最适合您的语言正确地实现应用程序,然后在运行太慢时找到性能瓶颈,然后考虑如何优化代码。在最坏的情况下,您可能需要通过一个外部函数接口调用C代码,因此您仍然能够在低级语言中编写关键的部分。
Keep in mind that it's relatively easy to optimize a correct program, but much harder to correct an optimized program.
请记住,优化一个正确的程序相对容易,但是修改一个优化过的程序要难得多。
Giving actual percentages of speed advantages is impossible, it largely depends on your code. In many cases, the programming language implementation isn't even the bottleneck. Take the benchmarks at http://benchmarksgame.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all.
给出速度优势的实际百分比是不可能的,这在很大程度上取决于您的代码。在许多情况下,编程语言实现甚至不是瓶颈。拿http://benchmarksgame.alioth.debian.org/上的基准进行大量的怀疑,因为这些主要测试算术代码,很可能与您的代码完全不同。
#2
166
C# may not be faster, but it makes YOU/ME faster. That's the most important measure for what I do. :)
c#可能不是更快,但它让你/我更快。这是我所做的最重要的衡量标准。:)
#3
74
It's five oranges faster. Or rather: there can be no (correct) blanket answer. C++ is a statically compiled language (but then, there's profile guided optimization, too), C# runs aided by a JIT compiler. There are so many differences that questions like “how much faster” cannot be answered, not even by giving orders of magnitude.
这是五个橘子更快。或者更确切地说:不可能有(正确的)全面的答案。c++是一种静态编译语言(但是,还有概要引导优化),c#在JIT编译器的帮助下运行。有很多不同的问题,比如“快多少”是不能回答的,即使是数量级也不行。
#4
53
In my experience (and I have worked a lot with both languages), the main problem with C# compared to C++ is high memory consumption, and I have not found a good way to control it. It was the memory consumption that would eventually slow down .NET software.
根据我的经验(我在两种语言上都做过很多工作),与c++相比,c#的主要问题是高内存消耗,我还没有找到一个好的方法来控制它。内存消耗最终会减慢。net软件的运行速度。
Another factor is that JIT compiler cannot afford too much time to do advanced optimizations, because it runs at runtime, and the end user would notice it if it takes too much time. On the other hand, a C++ compiler has all the time it needs to do optimizations at compile time. This factor is much less significant than memory consumption, IMHO.
另一个因素是JIT编译器不能提供太多的时间来进行高级优化,因为它在运行时运行,如果花费太多时间,最终用户会注意到它。另一方面,c++编译器在编译时一直需要进行优化。这个因素远不如内存消耗那么重要。
#5
46
I'm going to start by disagreeing with part of the accepted (and well-upvoted) answer to this question by stating:
首先,我要对这个问题的部分公认的(和良好的投票结果)的回答提出异议,我要说:
There are actually plenty of reasons why JITted code will run slower than a properly optimized C++ (or other language without runtime overhead) program including:
实际上,有很多原因可以解释为什么javen会比一个适当优化的c++(或者其他没有运行时开销的语言)程序运行得慢,包括:
-
compute cycles spent on JITting code at runtime are by definition unavailable for use in program execution.
根据定义,用于在运行时提取代码的计算周期在程序执行中不可用。
-
any hot paths in the JITter will be competing with your code for instruction and data cache in the CPU. We know that cache dominates when it comes to performance and native languages like C++, by definition, do not have this type of contention.
抖动中的任何热路径都将与您的代码竞争CPU中的指令和数据缓存。我们知道,缓存在性能方面占主导地位,而像c++这样的本地语言,根据定义,不存在这种类型的争用。
-
a run-time optimizer's time budget is necessarily much more constrained than that of a compile-time optimizer's (as another commenter pointed out)
运行时优化器的时间预算必然比编译时优化器的时间预算约束得多(正如另一位评论者指出的)
Bottom line: Ultimately, you will almost certainly be able to create a faster implementation in C++ than you could in C#.
底线:最终,您几乎肯定能够在c++中创建比在c#中更快的实现。
Now, with that said, how much faster really isn't quantifiable, as there are too many variables: the task, problem domain, hardware, quality of implementations, and many other factors. You'll have run tests on your scenario to decide whether the additional effort and complexity is worth it.
话虽如此,速度究竟有多快并不是可以量化的,因为有太多的变量:任务、问题域、硬件、实现的质量和许多其他因素。您将在您的场景中运行测试,以确定额外的工作和复杂性是否值得。
This is a very long and complex topic, but I feel it's worth mentioning for the sake of completeness that C#'s runtime optimizer is excellent, and is able to perform certain dynamic optimizations at runtime that are simply not available to C++ with its compile-time (static) optimizer. Even with this, the advantage is still typically deeply in the native application's court, but the dynamic optimizer is the reason for the "almost certainly" qualifier, given above.
这是一个很长很复杂的主题,但是为了完整性起见,我认为值得一提的是,c#的运行时优化器非常优秀,并且能够在运行时执行某些动态优化,而c++的编译时(静态)优化器根本无法执行这些优化。尽管如此,这种优势在本地应用程序中仍然非常明显,但是动态优化器是前面给出的“几乎肯定”限定符的原因。
--
- - -
In terms of relative performance, I was also disturbed by the figures and discussions I saw in some other answers, so I thought I'd chime in and at the same time, provide some support for the statements I've made above.
在相对的表现方面,我也被我在其他一些答案中看到的数字和讨论所困扰,所以我认为我应该在同时,为我上面所做的陈述提供一些支持。
A huge part of the problem with those benchmarks is you can't write C++ code as if you were writing C# and expect to get representative results (eg. performing thousands of memory allocations in C++ is going to give you terrible numbers.)
这些基准测试的一个很大的问题是,您不能像编写c#那样编写c++代码并期望得到具有代表性的结果(例如)。在c++中执行成千上万的内存分配会给你一个糟糕的数字。
Instead, I wrote slightly more idiomatic C++ code and compared against the C# code @Wiory provided. The two major changes I made to the C++ code were:
相反,我编写了稍微更惯用的c++代码,并与所提供的c#代码@Wiory进行了比较。我对c++代码做的两个主要改变是:
1) used vector::reserve()
1)使用向量::储备()
2) flattened the 2d array to 1d to achieve better cache locality (contiguous block)
2)将2d数组扁平化到1d,以实现更好的缓存局部性(连续块)
C# (.NET 4.6.1)
c#(。净4.6.1)
private static void TestArray()
{
const int rows = 5000;
const int columns = 9000;
DateTime t1 = System.DateTime.Now;
double[][] arr = new double[rows][];
for (int i = 0; i < rows; i++)
arr[i] = new double[columns];
DateTime t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
t1 = System.DateTime.Now;
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arr[i][j] = i;
t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
}
Run time (Release): Init: 124ms, Fill: 165ms
运行时(释放):Init: 124ms,填充:165ms。
C++14 (Clang v3.8/C2)
c++ 14(叮当声v3.8 / C2)
#include <iostream>
#include <vector>
auto TestSuite::ColMajorArray()
{
constexpr size_t ROWS = 5000;
constexpr size_t COLS = 9000;
auto initStart = std::chrono::steady_clock::now();
auto arr = std::vector<double>();
arr.reserve(ROWS * COLS);
auto initFinish = std::chrono::steady_clock::now();
auto initTime = std::chrono::duration_cast<std::chrono::microseconds>(initFinish - initStart);
auto fillStart = std::chrono::steady_clock::now();
for(auto i = 0, r = 0; r < ROWS; ++r)
{
for (auto c = 0; c < COLS; ++c)
{
arr[i++] = static_cast<double>(r * c);
}
}
auto fillFinish = std::chrono::steady_clock::now();
auto fillTime = std::chrono::duration_cast<std::chrono::milliseconds>(fillFinish - fillStart);
return std::make_pair(initTime, fillTime);
}
Run time (Release): Init: 398µs (yes, that's microseconds), Fill: 152ms
运行时间(释放):Init:398µs(是的,这是微秒),填写:152 ms
Total Run times: C#: 289ms, C++ 152ms (roughly 90% faster)
Observations
观察
-
Changing the C# implementation to the same 1d array implementation yielded Init: 40ms, Fill: 171ms, Total: 211ms (C++ was still almost 40% faster).
将c#实现更改为相同的1d数组实现产生了Init: 40ms,填充:171ms,总数:211ms (c++的速度仍然快40%)。
-
It is much harder to design and write "fast" code in C++ than it is to write "regular" code in either language.
用c++设计和编写“快速”代码比用两种语言编写“常规”代码要困难得多。
-
It's (perhaps) astonishingly easy to get poor performance in C++; we saw that with unreserved vectors performance. And there are lots of pitfalls like this.
(也许)很容易在c++中获得糟糕的性能;我们看到无保留向量的表现。像这样的陷阱有很多。
-
C#'s performance is rather amazing when you consider all that is going on at runtime. And that performance is comparatively easy to access.
当您考虑运行时发生的所有事情时,c#的性能是相当惊人的。这种性能比较容易获得。
-
More anecdotal data comparing the performance of C++ and C#: https://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=gpp&lang2=csharpcore
更多对比c++和c#性能的轶事数据:https://benchmarksgame.alioth.debian.org/u64q/compare.php?
The bottom line is that C++ gives you much more control over performance. Do you want to use a pointer? A reference? Stack memory? Heap? Dynamic polymorphism or eliminate the runtime overhead of a vtable with static polymorphism (via templates/CRTP)? In C++ you have to... er, get to make all these choices (and more) yourself, ideally so that your solution best addresses the problem you're tackling.
总之,c++为您提供了对性能的更多控制。你要用指针吗?一个参考吗?栈内存?堆吗?动态多态性还是通过静态多态性(通过模板/CRTP)消除vtable的运行时开销?在c++中,你必须……呃,你自己做所有这些选择(或者更多),最好是你的解决方案最好地解决你正在处理的问题。
Ask yourself if you actually want or need that control, because even for the trivial example above, you can see that although there is a significant improvement in performance, it requires a deeper investment to access.
问问你自己,你是否真的想要或者需要这样的控制,因为即使是上面这个微不足道的例子,你也可以看到,尽管性能有了显著的提高,但是访问需要更深入的投资。
#6
29
One particular scenario where C++ still has the upper hand (and will, for years to come) occurs when polymorphic decisions can be predetermined at compile time.
当可以在编译时预先确定多态决策时,会出现一种特定的场景,即c++仍然占上风(而且在未来数年仍将如此)。
Generally, encapsulation and deferred decision-making is a good thing because it makes the code more dynamic, easier to adapt to changing requirements and easier to use as a framework. This is why object oriented programming in C# is very productive and it can be generalized under the term “generalization”. Unfortunately, this particular kind of generalization comes at a cost at run-time.
通常,封装和延迟决策是一件好事,因为它使代码更有活力,更容易适应变化的需求,更容易作为框架使用。这就是为什么c#中的面向对象编程是非常有效的,并且可以在“一般化”一词下进行推广。不幸的是,这种特殊的泛化在运行时是有代价的。
Usually, this cost is non-substantial but there are applications where the overhead of virtual method calls and object creation can make a difference (especially since virtual methods prevent other optimizations such as method call inlining). This is where C++ has a huge advantage because you can use templates to achieve a different kind of generalization which has no impact on runtime but isn't necessarily any less polymorphic than OOP. In fact, all of the mechanisms that constitute OOP can be modelled using only template techniques and compile-time resolution.
通常,这种成本是非实质性的,但是在应用程序中,虚拟方法调用和对象创建的开销可以产生不同(特别是由于虚拟方法阻止了其他优化,比如方法调用内联)。这就是c++的巨大优势,因为您可以使用模板来实现一种不同的泛化,这种泛化对运行时没有影响,但并不一定比OOP少多少多态性。事实上,所有构成OOP的机制都可以仅使用模板技术和编译时解析来建模。
In such cases (and admittedly, they're often restricted to special problem domains), C++ wins against C# and comparable languages.
在这种情况下(必须承认,它们经常被限制在特殊的问题领域),c++战胜c#和类似的语言。
#7
16
For graphics the standard C# Graphics class is way slower than GDI accessed via C/C++. I know this has nothing to do with the language per se, more with the total .NET platform, but Graphics is what is offered to the developer as a GDI replacement, and its performance is so bad I wouldn't even dare to do graphics with it.
对于图形,标准的c#图形类比通过C/ c++访问的GDI要慢得多。我知道这和语言本身没有关系,更多的是和。net平台有关,但是图形是作为GDI的替代品提供给开发人员的,它的性能非常差,我甚至不敢用它来做图形。
We have a simple benchmark we use to see how fast a graphics library is, and that is simply drawing random lines in a window. C++/GDI is still snappy with 10000 lines while C#/Graphics has difficulty doing 1000 in real-time.
我们有一个简单的基准,用来查看图形库有多快,那就是在窗口中绘制随机的线条。c++ /GDI仍然有10000行代码,而c# /Graphics却很难实时处理1000行代码。
#8
16
C++ (or C for that matter) gives you fine-grained control over your data structures. If you want to bit-twiddle you have that option. Large managed Java or .NET apps (OWB, Visual Studio 2005) that use the internal data structures of the Java/.NET libraries carry the baggage with them. I've seen OWB designer sessions using over 400 MB of RAM and BIDS for cube or ETL design getting into the 100's of MB as well.
c++(或者C)提供了对数据结构的细粒度控制。如果你想耍小聪明,你可以选择。使用Java/的内部数据结构的大型托管Java或. net应用程序(OWB, Visual Studio 2005)。网络图书馆随身携带行李。我见过OWB设计人员会议使用超过400 MB的RAM,对cube或ETL设计的投标也达到了100 MB。
On a predictable workload (such as most benchmarks that repeat a process many times) a JIT can get you code that is optimised well enough that there is no practical difference.
在可预测的工作负载(例如多次重复一个过程的基准测试)上,JIT可以让您的代码优化得足够好,以至于没有实际的差异。
IMO on large applications the difference is not so much the JIT as the data structures that the code itself is using. Where an application is memory-heavy you will get less efficient cache usage. Cache misses on modern CPUs are quite expensive. Where C or C++ really win is where you can optimise your usage of data structures to play nicely with the CPU cache.
在大型应用程序上,差异不在于JIT,而在于代码本身使用的数据结构。当应用程序内存过多时,缓存使用率就会降低。现代cpu上的缓存丢失非常昂贵。在C或c++真正取得成功的地方,您可以优化您的数据结构的使用,以便与CPU缓存配合得很好。
#9
11
The garbage collection is the main reason Java# CANNOT be used for real-time systems.
垃圾收集是Java#不能用于实时系统的主要原因。
-
When will the GC happen?
GC什么时候发生?
-
How long will it take?
要花多长时间?
This is non-deterministic.
这是不确定的。
#10
11
We have had to determine if C# was comparable to C++ in performance and I wrote some test programs for that (using Visual Studio 2005 for both languages). It turned out that without garbage collection and only considering the language (not the framework) C# has basically the same performance as C++. Memory allocation is way faster in C# than in C++ and C# has a slight edge in determinism when data sizes are increased beyond cache line boundaries. However, all of this had eventually to be paid for and there is a huge cost in the form of non-deterministic performance hits for C# due to garbage collection.
我们必须确定c#在性能上是否可以与c++相比,我为此编写了一些测试程序(使用两种语言的Visual Studio 2005)。事实证明,没有垃圾收集,只考虑语言(不是框架),c#的性能基本上与c++相同。在c#中,内存分配比c++中快得多,当数据大小超出缓存线边界时,c#在决定论中有一点优势。然而,所有这一切最终都要付出代价,而且由于垃圾收集,c#的非确定性性能损失巨大。
#11
9
As usual, it depends on the application. There are cases where C# is probably negligibly slower, and other cases where C++ is 5 or 10 times faster, especially in cases where operations can be easily SIMD'd.
和往常一样,这取决于应用程序。有些情况下,c#的速度可能可以忽略不计,而有些情况下c++的速度要快5到10倍,特别是在操作容易简化的情况下。
#12
9
I know it isn't what you were asking, but C# is often quicker to write than C++, which is a big bonus in a commercial setting.
我知道这不是你想问的,但是c#通常比c++写得快,这在商业环境中是一个很大的好处。
#13
7
.NET languages can be as fast as C++ code, or even faster, but C++ code will have a more constant throughput as the .NET runtime has to pause for GC, even if it's very clever about its pauses.
. net语言可以和c++代码一样快,甚至更快,但是c++代码的吞吐量将更稳定,因为. net运行时必须暂停GC,即使它非常善于暂停。
So if you have some code that has to consistently run fast without any pause, .NET will introduce latency at some point, even if you are very careful with the runtime GC.
因此,如果您有一些代码必须始终快速运行而不需要任何停顿,. net将在某些时候引入延迟,即使您对运行时GC非常小心。
#14
6
C/C++ can perform vastly better in programs where there are either large arrays or heavy looping/iteration over arrays (of any size). This is the reason that graphics are generally much faster in C/C++, because heavy array operations underlie almost all graphics operations. .NET is notoriously slow in array indexing operations due to all the safety checks, and this is especially true for multi-dimensional arrays (and, yes, rectangular C# arrays are even slower than jagged C# arrays).
C/ c++可以在有大型数组或重循环/迭代(任何大小)的程序中执行得更好。这是图形的原因通常是在C / c++快得多,因为沉重的数组操作基础几乎所有的图形操作。net数组索引操作中是出了名的慢是因为所有的安全检查,和特别是多维数组(是的,矩形c#数组甚至低于参差不齐的c#数组)。
The bonuses of C/C++ are most pronounced if you stick directly with pointers and avoid Boost, std::vector
and other high-level containers, as well as inline
every small function possible. Use old-school arrays whenever possible. Yes, you will need more lines of code to accomplish the same thing you did in Java or C# as you avoid high-level containers. If you need a dynamically sized array, you will just need to remember to pair your new T[]
with a corresponding delete[]
statement (or use std::unique_ptr
)—the price for the extra speed is that you must code more carefully. But in exchange, you get to rid yourself of the overhead of managed memory / garbage collector, which can easily be 20% or more of the execution time of heavily object-oriented programs in both Java and .NET, as well as those massive managed memory array indexing costs. C++ apps can also benefit from some nifty compiler switches in certain specific cases.
如果您直接使用指针并避免Boost、std::vector和其他高级容器,以及尽可能内联每个小函数,那么C/ c++的加值将最为明显。尽可能使用老式数组。是的,您将需要更多的代码行来完成在Java或c#中所做的事情,因为您要避免高级容器。如果您需要一个动态大小的数组,您只需要记住将新的T[]与相应的delete[]语句(或者使用std::unique_ptr)进行配对——额外速度的代价是您必须更仔细地编写代码。但是作为交换,您可以摆脱托管内存/垃圾收集器的开销,它可以很容易地占Java和. net中大量面向对象程序执行时间的20%或更多,以及大量托管内存数组索引成本。在某些特定的情况下,c++应用程序还可以从一些漂亮的编译器切换中获益。
I am an expert programmer in C, C++, Java, and C#. I recently had the rare occasion to implement the exact same algorithmic program in the latter 3 languages. The program had a lot of math and multi-dimensional array operations. I heavily optimized this in all 3 languages. The results were typical of what I normally see in less rigorous comparisons: Java was about 1.3x faster than C# (most JVMs are more optimized than the CLR), and the C++ raw pointer version came in about 2.1x faster than C#. Note that the C# program only used safe code—it is my opinion that you might as well code it in C++ before using the unsafe
keyword.
我是一个精通C、c++、Java和c#的程序员。我最近很难得地用后三种语言实现了完全相同的算法程序。这个程序有很多数学运算和多维数组运算。我在这三种语言中都进行了大量的优化。结果是我通常在不太严格的比较中看到的典型结果:Java比c#快了大约1.3倍(大多数jvm都比CLR优化),c++原始指针版本比c#快了2.1倍。请注意,c#程序只使用了安全代码——我的观点是,在使用不安全的关键字之前,您最好在c++中编写代码。
Lest anyone think I have something against C#, I will close by saying that C# is probably my favorite language. It is the most logical, intuitive and rapid development language I've encountered so far. I do all my prototyping in C#. The C# language has many small, subtle advantages over Java (yes, I know Microsoft had the chance to fix many of Java's shortcomings by entering the game late and arguably copying Java). Toast to Java's Calendar
class anyone? If Microsoft ever spends real effort to optimize the CLR and the .NET JITter, C# could seriously take over. I'm honestly surprised they haven't already—they did so many things right in the C# language, why not follow it up with heavy-hitting compiler optimizations? Maybe if we all beg.
为了避免有人认为我反对c#,我最后要说c#可能是我最喜欢的语言。这是迄今为止我所遇到的最符合逻辑、最直观、最快速的开发语言。我在c#中做了所有的原型。与Java相比,c#语言有许多小的、微妙的优势(是的,我知道Microsoft有机会通过延迟进入游戏并复制Java来修复Java的许多缺点)。有人为Java的Calendar类干杯吗?如果微软花了真正的努力去优化CLR和。net抖动,c#将会真正接管。老实说,我很惊讶他们还没有——他们在c#语言中做了那么多正确的事情,为什么不继续进行重磅级的编译器优化呢?也许我们都要乞求。
#15
6
> From what I've heard ...
我听说……
Your difficulty seems to be in deciding whether what you have heard is credible, and that difficulty will just be repeated when you try to assess the replies on this site.
您的困难似乎在于决定您所听到的内容是否可信,而当您试图评估站点上的回复时,这种困难将再次出现。
How are you going to decide if the things people say here are more or less credible than what you originally heard?
你将如何决定人们在这里所说的事情是否比你最初听到的更可信?
One way would be to ask for evidence.
一种方法是要求证据。
When someone claims "there are some areas in which C# proves to be faster than C++" ask them why they say that, ask them to show you measurements, ask them to show you programs. Sometimes they will simply have made a mistake. Sometimes you'll find out that they are just expressing an opinion rather than sharing something that they can show to be true.
当有人声称“在某些领域,c#被证明比c++快”时,问问他们为什么这么说,让他们给你看测量数据,让他们给你看程序。有时他们只是犯了一个错误。有时候你会发现他们只是在表达自己的观点,而不是分享他们可以证明是真实的东西。
Often information and opinion will be mixed up in what people claim, and you'll have to try and sort out which is which. For example, from the replies in this forum:
通常情况下,人们的观点和信息会混淆在一起,你必须试着找出哪个是哪个。例如,从本论坛的回复中:
-
"Take the benchmarks at http://shootout.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all."
“拿http://shootout.alioth.debian.org/上的基准进行大量的怀疑,因为这些主要测试算术代码,很可能与您的代码完全不同。”
Ask yourself if you really understand what "these largely test arithmetic code" means, and then ask yourself if the author has actually shown you that his claim is true.
扪心自问,你是否真的理解“这些基本的算术代码”的含义,然后问自己,作者是否真的向你证明了他的观点是正确的。
-
"That's a rather useless test, since it really depends on how well the individual programs have been optimized; I've managed to speed up some of them by 4-6 times or more, making it clear that the comparison between unoptimized programs is rather silly."
这是一个相当无用的测试,因为它实际上取决于单个程序优化的程度;我已经设法将其中一些程序的速度提高了4-6倍或更多,这表明在未优化的程序之间进行比较是相当愚蠢的。
Ask yourself whether the author has actually shown you that he's managed to "speed up some of them by 4-6 times or more" - it's an easy claim to make!
问问你自己,作者是否真的向你展示了他“将其中的一些速度提高了4-6倍或更多”——这是一个很简单的说法!
#16
5
In theory, for long running server-type application, a JIT-compiled language can become much faster than a natively compiled counterpart. Since the JIT compiled language is generally first compiled to a fairly low-level intermediate language, you can do a lot of the high-level optimizations right at compile time anyway. The big advantage comes in that the JIT can continue to recompile sections of code on the fly as it gets more and more data on how the application is being used. It can arrange the most common code-paths to allow branch prediction to succeed as often as possible. It can re-arrange separate code blocks that are often called together to keep them both in the cache. It can spend more effort optimizing inner loops.
从理论上讲,对于长期运行的服务器类型应用程序,jit编译语言可以比本地编译的对等语言快得多。由于JIT编译语言通常首先被编译成一种相当低级的中间语言,因此您可以在编译时进行许多高级优化。最大的优势在于,当JIT获得越来越多关于应用程序使用方式的数据时,它可以动态地重新编译代码的各个部分。它可以安排最常见的代码路径,以便分支预测尽可能成功。它可以重新排列通常被调用的单独的代码块,以将它们保存在缓存中。它可以花费更多的精力来优化内部循环。
I doubt that this is done by .NET or any of the JREs, but it was being researched back when I was in university, so it's not unreasonable to think that these sort of things may find their way into the real world at some point soon.
我怀疑这是由。net或任何JREs完成的,但我在大学的时候就已经研究过了,所以认为这些东西会很快进入现实世界的想法是合理的。
#17
5
For 'embarassingly parallel' problems, when using Intel TBB and OpenMP on C++ I have observed a roughly 10x performance increase compared to similar (pure math) problems done with C# and TPL. SIMD is one area where C# cannot compete, but I also got the impression that TPL has a sizeable overhead.
对于“令人尴尬的并行”问题,当我在c++中使用Intel TBB和OpenMP时,我发现与使用c#和TPL处理的类似(纯数学)问题相比,性能提高了大约10倍。SIMD是c#无法竞争的领域之一,但我也有这样的印象:TPL有相当大的开销。
That said, I only use C++ for performance-critical tasks where I know I will be able to multithread and get results quickly. For everything else, C# (and occasionally F#) is just fine.
也就是说,我只在性能关键的任务中使用c++,因为我知道我可以多线程并快速地得到结果。除此之外,c#(偶尔f#)也很好。
#18
5
It's an extremely vague question without real definitive answers.
这是一个极其模糊的问题,没有确切的答案。
For example; I'd rather play 3D-games that are created in C++ than in C#, because the performance is certainly a lot better. (And I know XNA, etc., but it comes no way near the real thing).
例如;我宁愿玩c++开发的3d游戏,也不愿玩c#,因为性能肯定比c#好得多。(我知道XNA,等等,但它不可能接近真实的东西)。
On the other hand, as previously mentioned; you should develop in a language that lets you do what you want quickly, and then if necessary optimize.
另一方面,如前所述;您应该使用一种语言进行开发,该语言允许您快速地完成所需的工作,然后在必要时进行优化。
#19
4
Applications that require intensive memory access eg. image manipulation are usually better off written in unmanaged environment (C++) than managed (C#). Optimized inner loops with pointer arithmetics are much easier to have control of in C++. In C# you might need to resort to unsafe code to even get near the same performance.
需要密集内存访问的应用程序。在非托管环境(c++)中编写映像操作通常比在托管环境(c#)中编写映像更好。使用指针算法优化的内部循环更容易在c++中进行控制。在c#中,您可能需要使用不安全的代码来接近相同的性能。
#20
4
I've tested vector
in C++ and C# equivalent - List
and simple 2d arrays.
我已经在c++和c#等效列表和简单的2d数组中测试了vector。
I'm using Visual C#/C++ 2010 Express editions. Both projects are simple console applications, I've tested them in standard (no custom settings) release and debug mode. C# lists run faster on my pc, array initialization is also faster in C#, math operations are slower.
我使用的是Visual c# / c++ 2010 Express版本。这两个项目都是简单的控制台应用程序,我已经在标准(没有自定义设置)发布和调试模式中测试了它们。c#列表在我的pc上运行得更快,数组初始化在c#中也更快,数学运算也更慢。
I'm using Intel Core2Duo P8600@2.4GHz, C# - .NET 4.0.
我正在使用Intel Core2Duo P8600@2.4GHz, c# -。net 4.0。
I know that vector implementation is different than C# list, but I just wanted to test collections that I would use to store my objects (and being able to use index accessor).
我知道向量实现与c# list不同,但我只想测试我用来存储对象的集合(以及能够使用索引访问器)。
Of course you need to clear memory (let's say for every use of new
), but I wanted to keep the code simple.
当然,您需要清除内存(假设每次使用new),但我希望代码保持简单。
C++ vector test:
c++向量测试:
static void TestVector()
{
clock_t start,finish;
start=clock();
vector<vector<double>> myList=vector<vector<double>>();
int i=0;
for( i=0; i<500; i++)
{
myList.push_back(vector<double>());
for(int j=0;j<50000;j++)
myList[i].push_back(j+i);
}
finish=clock();
cout<<(finish-start)<<endl;
cout<<(double(finish - start)/CLOCKS_PER_SEC);
}
C# list test:
c#中测试:
private static void TestVector()
{
DateTime t1 = System.DateTime.Now;
List<List<double>> myList = new List<List<double>>();
int i = 0;
for (i = 0; i < 500; i++)
{
myList.Add(new List<double>());
for (int j = 0; j < 50000; j++)
myList[i].Add(j *i);
}
DateTime t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
}
C++ - array:
c++数组:
static void TestArray()
{
cout << "Normal array test:" << endl;
const int rows = 5000;
const int columns = 9000;
clock_t start, finish;
start = clock();
double** arr = new double*[rows];
for (int i = 0; i < rows; i++)
arr[i] = new double[columns];
finish = clock();
cout << (finish - start) << endl;
start = clock();
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arr[i][j] = i * j;
finish = clock();
cout << (finish - start) << endl;
}
C# - array:
c# -数组:
private static void TestArray()
{
const int rows = 5000;
const int columns = 9000;
DateTime t1 = System.DateTime.Now;
double[][] arr = new double[rows][];
for (int i = 0; i < rows; i++)
arr[i] = new double[columns];
DateTime t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
t1 = System.DateTime.Now;
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arr[i][j] = i * j;
t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
}
Time: (Release/Debug)
时间:(发布/调试)
C++
c++
- 600 / 606 ms array init,
- 600 / 606 ms数组init,
- 200 / 270 ms array fill,
- 200 / 270 ms阵列填充,
- 1sec /13sec vector init & fill.
- 1秒/13秒的矢量初始化和填充。
(Yes, 13 seconds, I always have problems with lists/vectors in debug mode.)
(是的,13秒,我总是在调试模式下遇到列表/向量的问题。)
C#:
c#:
- 20 / 20 ms array init,
- 20 ms数组init,
- 403 / 440 ms array fill,
- 403 / 440 ms阵列填充,
- 710 / 742 ms list init & fill.
- 710 / 742 ms列表初始化和填充。
#21
3
Well, it depends. If the byte-code is translated into machine-code (and not just JIT) (I mean if you execute the program) and if your program uses many allocations/deallocations it could be faster because the GC algorithm just need one pass (theoretically) through the whole memory once, but normal malloc/realloc/free C/C++ calls causes an overhead on every call (call-overhead, data-structure overhead, cache misses ;) ).
这得视情况而定。如果字节码转换成机器码(而不仅仅是JIT)(我的意思是如果你执行程序),如果您的程序使用了很多分配/回收它可以更快,因为GC算法只需要一个(理论上)穿过整个内存一次,但正常malloc / realloc /免费的C / c++电话导致的开销每个调用(调用开销,数据结构开销,缓存缺失;))。
So it is theoretically possible (also for other GC languages).
因此,这在理论上是可能的(对于其他GC语言也是如此)。
I don't really see the extreme disadvantage of not to be able to use metaprogramming with C# for the most applications, because the most programmers don't use it anyway.
我并没有真正看到不能在大多数应用程序中使用c#编程的极端缺点,因为大多数程序员都不使用它。
Another big advantage is that the SQL, like the LINQ "extension", provides opportunities for the compiler to optimize calls to databases (in other words, the compiler could compile the whole LINQ to one "blob" binary where the called functions are inlined or for your use optimized, but I'm speculating here).
另一个很大的优点是,SQL,如LINQ“扩展”,为编译器优化对数据库的调用提供了机会(换句话说,编译器可以将整个LINQ编译为一个“blob”二进制,其中所调用的函数是内联的,或者为您的使用进行优化,但是我在这里)。
#22
2
I suppose there are applications written in C# running fast, as well as there are more C++ written apps running fast (well C++ just older... and take UNIX too...)
- the question indeed is - what is that thing, users and developers are complaining about ...
Well, IMHO, in case of C# we have very comfort UI, very nice hierarchy of libraries, and whole interface system of CLI. In case of C++ we have templates, ATL, COM, MFC and whole shebang of alreadyc written and running code like OpenGL, DirectX and so on... Developers complains of indeterminably risen GC calls in case of C# (means program runs fast, and in one second - bang! it's stuck).
To write code in C# very simple and fast (not to forget that also increase chance of errors. In case of C++, developers complains of memory leaks, - means crushes, calls between DLLs, as well as of "DLL hell" - problem with support and replacement libraries by newer ones...
I think more skill you'll have in the programming language, the more quality (and speed) will characterize your software.
我猜想有一些用c#编写的应用程序运行得很快,也有更多c++编写的应用程序运行得很快(好吧,c++只是更老了……)问题是,用户和开发人员在抱怨什么呢?嗯,IMHO,对于c#,我们有非常舒适的UI,非常好的库层次结构,以及CLI的整个界面系统。对于c++,我们有模板、ATL、COM、MFC和完整的已经编写和运行的代码,比如OpenGL、DirectX等等……开发人员抱怨在c#(意味着程序运行得很快,并且在一秒钟内——砰!这是卡)。用c#编写代码非常简单和快速(不要忘记这也增加了出错的几率。在c++的情况下,开发人员抱怨内存泄漏,-意味着crush, DLL之间的调用,以及“DLL hell”——新版本的支持和替换库的问题……我认为你在编程语言中掌握的技能越多,你的软件就越有质量(和速度)。
#23
2
I would put it this way: programmers who write faster code, are the ones who are the more informed of what makes current machines go fast, and incidentally they are also the ones who use an appropriate tool that allows for precise low-level and deterministic optimisation techniques. For these reasons, these people are the ones who use C/C++ rather than C#. I would go as far as stating this as a fact.
我是这样说的:编写速度更快的代码的程序员更了解是什么使当前的机器运行得更快,顺便说一句,他们也使用合适的工具,允许精确的低层次和确定性优化技术。由于这些原因,这些人使用的是C/ c++而不是c#。我甚至认为这是事实。
#24
2
If I'm not mistaken, C# templates are determined at runtime. This must be slower than compile time templates of C++.
如果我没弄错的话,c#模板是在运行时确定的。这必须比c++的编译时模板慢。
And when you take in all the other compile-time optimizations mentioned by so many others, as well as the lack of safety that does, indeed, mean more speed...
当你考虑到其他许多人提到的所有编译时优化,以及安全性的缺乏,确实意味着更高的速度……
I'd say C++ is the obvious choice in terms of raw speed and minimum memory consumption. But this also translates into more time developing the code and ensuring you aren't leaking memory or causing any null pointer exceptions.
从原始速度和最小内存消耗来看,c++是显而易见的选择。但这也意味着要花更多时间开发代码,并确保不会泄漏内存或导致任何空指针异常。
Verdict:
结论:
-
C#: Faster development, slower run
更快的开发,更慢的运行
-
C++: Slow development, faster run.
c++:开发速度慢,运行速度快。
#25
1
> After all, the answers have to be somewhere, haven't they? :)
毕竟,答案一定在某个地方,不是吗?:)
Umm, no.
嗯,没有。
As several replies noted, the question is under-specified in ways that invite questions in response, not answers. To take just one way:
正如一些答复所指出的,这个问题没有得到充分的说明,而是以提问的方式来回答,而不是回答。就这么简单:
- the question conflates language with language implementation - this C program is both 2,194 times slower and 1.17 times faster than this C# program - we would have to ask you: Which language implementations?
- 这个问题将语言和语言实现混为一谈——这个C程序比这个c#程序慢2194倍,快1.17倍——我们不得不问你:哪种语言实现?
And then which programs? Which machine? Which OS? Which data set?
然后哪个项目?哪个机器?哪些操作系统?数据集?
#26
0
It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.
这真的取决于你想在你的代码中完成什么。我听说VB的性能有什么不同,这只是一个都市传说。NET、c#和托管c++。然而,我发现,至少在字符串比较中,托管c++击败了c#, c#反过来又击败了VB.NET。
I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.
我并没有对语言之间的算法复杂性做过任何详尽的比较。我还在每种语言中使用默认设置。在VB。NET我正在使用设置来要求声明变量,等等。这是我在托管c++中使用的代码(正如您所看到的,这段代码非常简单)。在Visual Studio 2013中,我使用。net 4.6.2运行了相同的其他语言。
#include "stdafx.h"
using namespace System;
using namespace System::Diagnostics;
bool EqualMe(String^ first, String^ second)
{
return first->Equals(second);
}
int main(array<String ^> ^args)
{
Stopwatch^ sw = gcnew Stopwatch();
sw->Start();
for (int i = 0; i < 100000; i++)
{
EqualMe(L"one", L"two");
}
sw->Stop();
Console::WriteLine(sw->ElapsedTicks);
return 0;
}
#27
-10
Inspired by this, I did a quick test with 60 percent of common instruction needed in most of the programs.
受此启发,我做了一个快速测试,在大多数程序中需要60%的常用指令。
Here’s the C# code:
这里的c#代码:
for (int i=0; i<1000; i++)
{
StreamReader str = new StreamReader("file.csv");
StreamWriter stw = new StreamWriter("examp.csv");
string strL = "";
while((strL = str.ReadLine()) != null)
{
ArrayList al = new ArrayList();
string[] strline = strL.Split(',');
al.AddRange(strline);
foreach(string str1 in strline)
{
stw.Write(str1 + ",");
}
stw.Write("\n");
}
str.Close();
stw.Close();
}
String array and arraylist are used purposely to include those instructions.
字符串数组和arraylist被故意用于包含这些指令。
Here's the c++ code:
这里的c++代码:
for (int i = 0; i<1000; i++)
{
std::fstream file("file.csv", ios::in);
if (!file.is_open())
{
std::cout << "File not found!\n";
return 1;
}
ofstream myfile;
myfile.open ("example.txt");
std::string csvLine;
while (std::getline(file, csvLine))
{
std::istringstream csvStream(csvLine);
std::vector csvColumn;
std::string csvElement;
while( std::getline(csvStream, csvElement, ‘,’) )
{
csvColumn.push_back(csvElement);
}
for (std::vector::iterator j = csvColumn.begin(); j != csvColumn.end(); ++j)
{
myfile << *j << ", ";
}
csvColumn.clear();
csvElement.clear();
csvLine.clear();
myfile << "\n";
}
myfile.close();
file.close();
}
The input file size I used was 40 KB.
我使用的输入文件大小是40kb。
And here's the result -
这是结果-
- C++ code ran in 9 seconds.
- c++代码在9秒内运行。
- C# code: 4 seconds!!!
- c#代码:4秒! ! !
Oh, but this was on Linux... With C# running on Mono... And C++ with g++.
哦,但是这是在Linux上……c#运行在Mono上…与g和C + + + +。
OK, this is what I got on Windows – Visual Studio 2003:
这是我在Windows - Visual Studio 2003上看到的
- C# code ran in 9 seconds.
- c#代码在9秒内运行。
- C++ code – horrible 370 seconds!!!
- c++代码-可怕的370秒!!
#1
280
There is no strict reason why a bytecode based language like C# or Java that has a JIT cannot be as fast as C++ code. However C++ code used to be significantly faster for a long time, and also today still is in many cases. This is mainly due to the more advanced JIT optimizations being complicated to implement, and the really cool ones are only arriving just now.
基于字节码的语言(如c#或Java)具有JIT的速度不如c++代码快,这是没有严格原因的。然而,c++代码在很长一段时间内都是非常快的,而且在很多情况下仍然是如此。这主要是由于更高级的JIT优化变得复杂而难以实现,而真正酷的JIT现在才刚刚到达。
So C++ is faster, in many cases. But this is only part of the answer. The cases where C++ is actually faster, are highly optimized programs, where expert programmers thoroughly optimized the hell out of the code. This is not only very time consuming (and thus expensive), but also commonly leads to errors due to over-optimizations.
所以在很多情况下,c++更快。但这只是答案的一部分。c++实际上更快的例子是高度优化的程序,在这些例子中,专家程序员彻底优化了代码。这不仅非常耗时(因此也很昂贵),而且由于过度优化,通常还会导致错误。
On the other hand, code in interpreted languages gets faster in later versions of the runtime (.NET CLR or Java VM), without you doing anything. And there are a lot of useful optimizations JIT compilers can do that are simply impossible in languages with pointers. Also, some argue that garbage collection should generally be as fast or faster as manual memory management, and in many cases it is. You can generally implement and achieve all of this in C++ or C, but it's going to be much more complicated and error prone.
另一方面,解释性语言中的代码在运行时(运行时)的后续版本中变得更快。NET CLR或Java VM),没有您做任何事情。JIT编译器可以做很多有用的优化,它们在语言中是不可能有指针的。此外,一些人认为垃圾收集通常应该和手动内存管理一样快或更快,在很多情况下确实如此。一般来说,您可以在c++或C语言中实现并实现所有这些功能,但这将更加复杂,并且容易出错。
As Donald Knuth said, "premature optimization is the root of all evil". If you really know for sure that your application will mostly consist of very performance critical arithmetic, and that it will be the bottleneck, and it's certainly going to be faster in C++, and you're sure that C++ won't conflict with your other requirements, go for C++. In any other case, concentrate on first implementing your application correctly in whatever language suits you best, then find performance bottlenecks if it runs too slow, and then think about how to optimize the code. In the worst case, you might need to call out to C code through a foreign function interface, so you'll still have the ability to write critical parts in lower level language.
正如Donald Knuth所说,“过早优化是万恶之源”。如果您确信您的应用程序将主要由非常关键的性能算法组成,并且它将成为瓶颈,并且在c++中肯定会更快,并且您确信c++不会与您的其他需求冲突,那么就使用c++吧。在任何其他情况下,首先集中精力以最适合您的语言正确地实现应用程序,然后在运行太慢时找到性能瓶颈,然后考虑如何优化代码。在最坏的情况下,您可能需要通过一个外部函数接口调用C代码,因此您仍然能够在低级语言中编写关键的部分。
Keep in mind that it's relatively easy to optimize a correct program, but much harder to correct an optimized program.
请记住,优化一个正确的程序相对容易,但是修改一个优化过的程序要难得多。
Giving actual percentages of speed advantages is impossible, it largely depends on your code. In many cases, the programming language implementation isn't even the bottleneck. Take the benchmarks at http://benchmarksgame.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all.
给出速度优势的实际百分比是不可能的,这在很大程度上取决于您的代码。在许多情况下,编程语言实现甚至不是瓶颈。拿http://benchmarksgame.alioth.debian.org/上的基准进行大量的怀疑,因为这些主要测试算术代码,很可能与您的代码完全不同。
#2
166
C# may not be faster, but it makes YOU/ME faster. That's the most important measure for what I do. :)
c#可能不是更快,但它让你/我更快。这是我所做的最重要的衡量标准。:)
#3
74
It's five oranges faster. Or rather: there can be no (correct) blanket answer. C++ is a statically compiled language (but then, there's profile guided optimization, too), C# runs aided by a JIT compiler. There are so many differences that questions like “how much faster” cannot be answered, not even by giving orders of magnitude.
这是五个橘子更快。或者更确切地说:不可能有(正确的)全面的答案。c++是一种静态编译语言(但是,还有概要引导优化),c#在JIT编译器的帮助下运行。有很多不同的问题,比如“快多少”是不能回答的,即使是数量级也不行。
#4
53
In my experience (and I have worked a lot with both languages), the main problem with C# compared to C++ is high memory consumption, and I have not found a good way to control it. It was the memory consumption that would eventually slow down .NET software.
根据我的经验(我在两种语言上都做过很多工作),与c++相比,c#的主要问题是高内存消耗,我还没有找到一个好的方法来控制它。内存消耗最终会减慢。net软件的运行速度。
Another factor is that JIT compiler cannot afford too much time to do advanced optimizations, because it runs at runtime, and the end user would notice it if it takes too much time. On the other hand, a C++ compiler has all the time it needs to do optimizations at compile time. This factor is much less significant than memory consumption, IMHO.
另一个因素是JIT编译器不能提供太多的时间来进行高级优化,因为它在运行时运行,如果花费太多时间,最终用户会注意到它。另一方面,c++编译器在编译时一直需要进行优化。这个因素远不如内存消耗那么重要。
#5
46
I'm going to start by disagreeing with part of the accepted (and well-upvoted) answer to this question by stating:
首先,我要对这个问题的部分公认的(和良好的投票结果)的回答提出异议,我要说:
There are actually plenty of reasons why JITted code will run slower than a properly optimized C++ (or other language without runtime overhead) program including:
实际上,有很多原因可以解释为什么javen会比一个适当优化的c++(或者其他没有运行时开销的语言)程序运行得慢,包括:
-
compute cycles spent on JITting code at runtime are by definition unavailable for use in program execution.
根据定义,用于在运行时提取代码的计算周期在程序执行中不可用。
-
any hot paths in the JITter will be competing with your code for instruction and data cache in the CPU. We know that cache dominates when it comes to performance and native languages like C++, by definition, do not have this type of contention.
抖动中的任何热路径都将与您的代码竞争CPU中的指令和数据缓存。我们知道,缓存在性能方面占主导地位,而像c++这样的本地语言,根据定义,不存在这种类型的争用。
-
a run-time optimizer's time budget is necessarily much more constrained than that of a compile-time optimizer's (as another commenter pointed out)
运行时优化器的时间预算必然比编译时优化器的时间预算约束得多(正如另一位评论者指出的)
Bottom line: Ultimately, you will almost certainly be able to create a faster implementation in C++ than you could in C#.
底线:最终,您几乎肯定能够在c++中创建比在c#中更快的实现。
Now, with that said, how much faster really isn't quantifiable, as there are too many variables: the task, problem domain, hardware, quality of implementations, and many other factors. You'll have run tests on your scenario to decide whether the additional effort and complexity is worth it.
话虽如此,速度究竟有多快并不是可以量化的,因为有太多的变量:任务、问题域、硬件、实现的质量和许多其他因素。您将在您的场景中运行测试,以确定额外的工作和复杂性是否值得。
This is a very long and complex topic, but I feel it's worth mentioning for the sake of completeness that C#'s runtime optimizer is excellent, and is able to perform certain dynamic optimizations at runtime that are simply not available to C++ with its compile-time (static) optimizer. Even with this, the advantage is still typically deeply in the native application's court, but the dynamic optimizer is the reason for the "almost certainly" qualifier, given above.
这是一个很长很复杂的主题,但是为了完整性起见,我认为值得一提的是,c#的运行时优化器非常优秀,并且能够在运行时执行某些动态优化,而c++的编译时(静态)优化器根本无法执行这些优化。尽管如此,这种优势在本地应用程序中仍然非常明显,但是动态优化器是前面给出的“几乎肯定”限定符的原因。
--
- - -
In terms of relative performance, I was also disturbed by the figures and discussions I saw in some other answers, so I thought I'd chime in and at the same time, provide some support for the statements I've made above.
在相对的表现方面,我也被我在其他一些答案中看到的数字和讨论所困扰,所以我认为我应该在同时,为我上面所做的陈述提供一些支持。
A huge part of the problem with those benchmarks is you can't write C++ code as if you were writing C# and expect to get representative results (eg. performing thousands of memory allocations in C++ is going to give you terrible numbers.)
这些基准测试的一个很大的问题是,您不能像编写c#那样编写c++代码并期望得到具有代表性的结果(例如)。在c++中执行成千上万的内存分配会给你一个糟糕的数字。
Instead, I wrote slightly more idiomatic C++ code and compared against the C# code @Wiory provided. The two major changes I made to the C++ code were:
相反,我编写了稍微更惯用的c++代码,并与所提供的c#代码@Wiory进行了比较。我对c++代码做的两个主要改变是:
1) used vector::reserve()
1)使用向量::储备()
2) flattened the 2d array to 1d to achieve better cache locality (contiguous block)
2)将2d数组扁平化到1d,以实现更好的缓存局部性(连续块)
C# (.NET 4.6.1)
c#(。净4.6.1)
private static void TestArray()
{
const int rows = 5000;
const int columns = 9000;
DateTime t1 = System.DateTime.Now;
double[][] arr = new double[rows][];
for (int i = 0; i < rows; i++)
arr[i] = new double[columns];
DateTime t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
t1 = System.DateTime.Now;
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arr[i][j] = i;
t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
}
Run time (Release): Init: 124ms, Fill: 165ms
运行时(释放):Init: 124ms,填充:165ms。
C++14 (Clang v3.8/C2)
c++ 14(叮当声v3.8 / C2)
#include <iostream>
#include <vector>
auto TestSuite::ColMajorArray()
{
constexpr size_t ROWS = 5000;
constexpr size_t COLS = 9000;
auto initStart = std::chrono::steady_clock::now();
auto arr = std::vector<double>();
arr.reserve(ROWS * COLS);
auto initFinish = std::chrono::steady_clock::now();
auto initTime = std::chrono::duration_cast<std::chrono::microseconds>(initFinish - initStart);
auto fillStart = std::chrono::steady_clock::now();
for(auto i = 0, r = 0; r < ROWS; ++r)
{
for (auto c = 0; c < COLS; ++c)
{
arr[i++] = static_cast<double>(r * c);
}
}
auto fillFinish = std::chrono::steady_clock::now();
auto fillTime = std::chrono::duration_cast<std::chrono::milliseconds>(fillFinish - fillStart);
return std::make_pair(initTime, fillTime);
}
Run time (Release): Init: 398µs (yes, that's microseconds), Fill: 152ms
运行时间(释放):Init:398µs(是的,这是微秒),填写:152 ms
Total Run times: C#: 289ms, C++ 152ms (roughly 90% faster)
Observations
观察
-
Changing the C# implementation to the same 1d array implementation yielded Init: 40ms, Fill: 171ms, Total: 211ms (C++ was still almost 40% faster).
将c#实现更改为相同的1d数组实现产生了Init: 40ms,填充:171ms,总数:211ms (c++的速度仍然快40%)。
-
It is much harder to design and write "fast" code in C++ than it is to write "regular" code in either language.
用c++设计和编写“快速”代码比用两种语言编写“常规”代码要困难得多。
-
It's (perhaps) astonishingly easy to get poor performance in C++; we saw that with unreserved vectors performance. And there are lots of pitfalls like this.
(也许)很容易在c++中获得糟糕的性能;我们看到无保留向量的表现。像这样的陷阱有很多。
-
C#'s performance is rather amazing when you consider all that is going on at runtime. And that performance is comparatively easy to access.
当您考虑运行时发生的所有事情时,c#的性能是相当惊人的。这种性能比较容易获得。
-
More anecdotal data comparing the performance of C++ and C#: https://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=gpp&lang2=csharpcore
更多对比c++和c#性能的轶事数据:https://benchmarksgame.alioth.debian.org/u64q/compare.php?
The bottom line is that C++ gives you much more control over performance. Do you want to use a pointer? A reference? Stack memory? Heap? Dynamic polymorphism or eliminate the runtime overhead of a vtable with static polymorphism (via templates/CRTP)? In C++ you have to... er, get to make all these choices (and more) yourself, ideally so that your solution best addresses the problem you're tackling.
总之,c++为您提供了对性能的更多控制。你要用指针吗?一个参考吗?栈内存?堆吗?动态多态性还是通过静态多态性(通过模板/CRTP)消除vtable的运行时开销?在c++中,你必须……呃,你自己做所有这些选择(或者更多),最好是你的解决方案最好地解决你正在处理的问题。
Ask yourself if you actually want or need that control, because even for the trivial example above, you can see that although there is a significant improvement in performance, it requires a deeper investment to access.
问问你自己,你是否真的想要或者需要这样的控制,因为即使是上面这个微不足道的例子,你也可以看到,尽管性能有了显著的提高,但是访问需要更深入的投资。
#6
29
One particular scenario where C++ still has the upper hand (and will, for years to come) occurs when polymorphic decisions can be predetermined at compile time.
当可以在编译时预先确定多态决策时,会出现一种特定的场景,即c++仍然占上风(而且在未来数年仍将如此)。
Generally, encapsulation and deferred decision-making is a good thing because it makes the code more dynamic, easier to adapt to changing requirements and easier to use as a framework. This is why object oriented programming in C# is very productive and it can be generalized under the term “generalization”. Unfortunately, this particular kind of generalization comes at a cost at run-time.
通常,封装和延迟决策是一件好事,因为它使代码更有活力,更容易适应变化的需求,更容易作为框架使用。这就是为什么c#中的面向对象编程是非常有效的,并且可以在“一般化”一词下进行推广。不幸的是,这种特殊的泛化在运行时是有代价的。
Usually, this cost is non-substantial but there are applications where the overhead of virtual method calls and object creation can make a difference (especially since virtual methods prevent other optimizations such as method call inlining). This is where C++ has a huge advantage because you can use templates to achieve a different kind of generalization which has no impact on runtime but isn't necessarily any less polymorphic than OOP. In fact, all of the mechanisms that constitute OOP can be modelled using only template techniques and compile-time resolution.
通常,这种成本是非实质性的,但是在应用程序中,虚拟方法调用和对象创建的开销可以产生不同(特别是由于虚拟方法阻止了其他优化,比如方法调用内联)。这就是c++的巨大优势,因为您可以使用模板来实现一种不同的泛化,这种泛化对运行时没有影响,但并不一定比OOP少多少多态性。事实上,所有构成OOP的机制都可以仅使用模板技术和编译时解析来建模。
In such cases (and admittedly, they're often restricted to special problem domains), C++ wins against C# and comparable languages.
在这种情况下(必须承认,它们经常被限制在特殊的问题领域),c++战胜c#和类似的语言。
#7
16
For graphics the standard C# Graphics class is way slower than GDI accessed via C/C++. I know this has nothing to do with the language per se, more with the total .NET platform, but Graphics is what is offered to the developer as a GDI replacement, and its performance is so bad I wouldn't even dare to do graphics with it.
对于图形,标准的c#图形类比通过C/ c++访问的GDI要慢得多。我知道这和语言本身没有关系,更多的是和。net平台有关,但是图形是作为GDI的替代品提供给开发人员的,它的性能非常差,我甚至不敢用它来做图形。
We have a simple benchmark we use to see how fast a graphics library is, and that is simply drawing random lines in a window. C++/GDI is still snappy with 10000 lines while C#/Graphics has difficulty doing 1000 in real-time.
我们有一个简单的基准,用来查看图形库有多快,那就是在窗口中绘制随机的线条。c++ /GDI仍然有10000行代码,而c# /Graphics却很难实时处理1000行代码。
#8
16
C++ (or C for that matter) gives you fine-grained control over your data structures. If you want to bit-twiddle you have that option. Large managed Java or .NET apps (OWB, Visual Studio 2005) that use the internal data structures of the Java/.NET libraries carry the baggage with them. I've seen OWB designer sessions using over 400 MB of RAM and BIDS for cube or ETL design getting into the 100's of MB as well.
c++(或者C)提供了对数据结构的细粒度控制。如果你想耍小聪明,你可以选择。使用Java/的内部数据结构的大型托管Java或. net应用程序(OWB, Visual Studio 2005)。网络图书馆随身携带行李。我见过OWB设计人员会议使用超过400 MB的RAM,对cube或ETL设计的投标也达到了100 MB。
On a predictable workload (such as most benchmarks that repeat a process many times) a JIT can get you code that is optimised well enough that there is no practical difference.
在可预测的工作负载(例如多次重复一个过程的基准测试)上,JIT可以让您的代码优化得足够好,以至于没有实际的差异。
IMO on large applications the difference is not so much the JIT as the data structures that the code itself is using. Where an application is memory-heavy you will get less efficient cache usage. Cache misses on modern CPUs are quite expensive. Where C or C++ really win is where you can optimise your usage of data structures to play nicely with the CPU cache.
在大型应用程序上,差异不在于JIT,而在于代码本身使用的数据结构。当应用程序内存过多时,缓存使用率就会降低。现代cpu上的缓存丢失非常昂贵。在C或c++真正取得成功的地方,您可以优化您的数据结构的使用,以便与CPU缓存配合得很好。
#9
11
The garbage collection is the main reason Java# CANNOT be used for real-time systems.
垃圾收集是Java#不能用于实时系统的主要原因。
-
When will the GC happen?
GC什么时候发生?
-
How long will it take?
要花多长时间?
This is non-deterministic.
这是不确定的。
#10
11
We have had to determine if C# was comparable to C++ in performance and I wrote some test programs for that (using Visual Studio 2005 for both languages). It turned out that without garbage collection and only considering the language (not the framework) C# has basically the same performance as C++. Memory allocation is way faster in C# than in C++ and C# has a slight edge in determinism when data sizes are increased beyond cache line boundaries. However, all of this had eventually to be paid for and there is a huge cost in the form of non-deterministic performance hits for C# due to garbage collection.
我们必须确定c#在性能上是否可以与c++相比,我为此编写了一些测试程序(使用两种语言的Visual Studio 2005)。事实证明,没有垃圾收集,只考虑语言(不是框架),c#的性能基本上与c++相同。在c#中,内存分配比c++中快得多,当数据大小超出缓存线边界时,c#在决定论中有一点优势。然而,所有这一切最终都要付出代价,而且由于垃圾收集,c#的非确定性性能损失巨大。
#11
9
As usual, it depends on the application. There are cases where C# is probably negligibly slower, and other cases where C++ is 5 or 10 times faster, especially in cases where operations can be easily SIMD'd.
和往常一样,这取决于应用程序。有些情况下,c#的速度可能可以忽略不计,而有些情况下c++的速度要快5到10倍,特别是在操作容易简化的情况下。
#12
9
I know it isn't what you were asking, but C# is often quicker to write than C++, which is a big bonus in a commercial setting.
我知道这不是你想问的,但是c#通常比c++写得快,这在商业环境中是一个很大的好处。
#13
7
.NET languages can be as fast as C++ code, or even faster, but C++ code will have a more constant throughput as the .NET runtime has to pause for GC, even if it's very clever about its pauses.
. net语言可以和c++代码一样快,甚至更快,但是c++代码的吞吐量将更稳定,因为. net运行时必须暂停GC,即使它非常善于暂停。
So if you have some code that has to consistently run fast without any pause, .NET will introduce latency at some point, even if you are very careful with the runtime GC.
因此,如果您有一些代码必须始终快速运行而不需要任何停顿,. net将在某些时候引入延迟,即使您对运行时GC非常小心。
#14
6
C/C++ can perform vastly better in programs where there are either large arrays or heavy looping/iteration over arrays (of any size). This is the reason that graphics are generally much faster in C/C++, because heavy array operations underlie almost all graphics operations. .NET is notoriously slow in array indexing operations due to all the safety checks, and this is especially true for multi-dimensional arrays (and, yes, rectangular C# arrays are even slower than jagged C# arrays).
C/ c++可以在有大型数组或重循环/迭代(任何大小)的程序中执行得更好。这是图形的原因通常是在C / c++快得多,因为沉重的数组操作基础几乎所有的图形操作。net数组索引操作中是出了名的慢是因为所有的安全检查,和特别是多维数组(是的,矩形c#数组甚至低于参差不齐的c#数组)。
The bonuses of C/C++ are most pronounced if you stick directly with pointers and avoid Boost, std::vector
and other high-level containers, as well as inline
every small function possible. Use old-school arrays whenever possible. Yes, you will need more lines of code to accomplish the same thing you did in Java or C# as you avoid high-level containers. If you need a dynamically sized array, you will just need to remember to pair your new T[]
with a corresponding delete[]
statement (or use std::unique_ptr
)—the price for the extra speed is that you must code more carefully. But in exchange, you get to rid yourself of the overhead of managed memory / garbage collector, which can easily be 20% or more of the execution time of heavily object-oriented programs in both Java and .NET, as well as those massive managed memory array indexing costs. C++ apps can also benefit from some nifty compiler switches in certain specific cases.
如果您直接使用指针并避免Boost、std::vector和其他高级容器,以及尽可能内联每个小函数,那么C/ c++的加值将最为明显。尽可能使用老式数组。是的,您将需要更多的代码行来完成在Java或c#中所做的事情,因为您要避免高级容器。如果您需要一个动态大小的数组,您只需要记住将新的T[]与相应的delete[]语句(或者使用std::unique_ptr)进行配对——额外速度的代价是您必须更仔细地编写代码。但是作为交换,您可以摆脱托管内存/垃圾收集器的开销,它可以很容易地占Java和. net中大量面向对象程序执行时间的20%或更多,以及大量托管内存数组索引成本。在某些特定的情况下,c++应用程序还可以从一些漂亮的编译器切换中获益。
I am an expert programmer in C, C++, Java, and C#. I recently had the rare occasion to implement the exact same algorithmic program in the latter 3 languages. The program had a lot of math and multi-dimensional array operations. I heavily optimized this in all 3 languages. The results were typical of what I normally see in less rigorous comparisons: Java was about 1.3x faster than C# (most JVMs are more optimized than the CLR), and the C++ raw pointer version came in about 2.1x faster than C#. Note that the C# program only used safe code—it is my opinion that you might as well code it in C++ before using the unsafe
keyword.
我是一个精通C、c++、Java和c#的程序员。我最近很难得地用后三种语言实现了完全相同的算法程序。这个程序有很多数学运算和多维数组运算。我在这三种语言中都进行了大量的优化。结果是我通常在不太严格的比较中看到的典型结果:Java比c#快了大约1.3倍(大多数jvm都比CLR优化),c++原始指针版本比c#快了2.1倍。请注意,c#程序只使用了安全代码——我的观点是,在使用不安全的关键字之前,您最好在c++中编写代码。
Lest anyone think I have something against C#, I will close by saying that C# is probably my favorite language. It is the most logical, intuitive and rapid development language I've encountered so far. I do all my prototyping in C#. The C# language has many small, subtle advantages over Java (yes, I know Microsoft had the chance to fix many of Java's shortcomings by entering the game late and arguably copying Java). Toast to Java's Calendar
class anyone? If Microsoft ever spends real effort to optimize the CLR and the .NET JITter, C# could seriously take over. I'm honestly surprised they haven't already—they did so many things right in the C# language, why not follow it up with heavy-hitting compiler optimizations? Maybe if we all beg.
为了避免有人认为我反对c#,我最后要说c#可能是我最喜欢的语言。这是迄今为止我所遇到的最符合逻辑、最直观、最快速的开发语言。我在c#中做了所有的原型。与Java相比,c#语言有许多小的、微妙的优势(是的,我知道Microsoft有机会通过延迟进入游戏并复制Java来修复Java的许多缺点)。有人为Java的Calendar类干杯吗?如果微软花了真正的努力去优化CLR和。net抖动,c#将会真正接管。老实说,我很惊讶他们还没有——他们在c#语言中做了那么多正确的事情,为什么不继续进行重磅级的编译器优化呢?也许我们都要乞求。
#15
6
> From what I've heard ...
我听说……
Your difficulty seems to be in deciding whether what you have heard is credible, and that difficulty will just be repeated when you try to assess the replies on this site.
您的困难似乎在于决定您所听到的内容是否可信,而当您试图评估站点上的回复时,这种困难将再次出现。
How are you going to decide if the things people say here are more or less credible than what you originally heard?
你将如何决定人们在这里所说的事情是否比你最初听到的更可信?
One way would be to ask for evidence.
一种方法是要求证据。
When someone claims "there are some areas in which C# proves to be faster than C++" ask them why they say that, ask them to show you measurements, ask them to show you programs. Sometimes they will simply have made a mistake. Sometimes you'll find out that they are just expressing an opinion rather than sharing something that they can show to be true.
当有人声称“在某些领域,c#被证明比c++快”时,问问他们为什么这么说,让他们给你看测量数据,让他们给你看程序。有时他们只是犯了一个错误。有时候你会发现他们只是在表达自己的观点,而不是分享他们可以证明是真实的东西。
Often information and opinion will be mixed up in what people claim, and you'll have to try and sort out which is which. For example, from the replies in this forum:
通常情况下,人们的观点和信息会混淆在一起,你必须试着找出哪个是哪个。例如,从本论坛的回复中:
-
"Take the benchmarks at http://shootout.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all."
“拿http://shootout.alioth.debian.org/上的基准进行大量的怀疑,因为这些主要测试算术代码,很可能与您的代码完全不同。”
Ask yourself if you really understand what "these largely test arithmetic code" means, and then ask yourself if the author has actually shown you that his claim is true.
扪心自问,你是否真的理解“这些基本的算术代码”的含义,然后问自己,作者是否真的向你证明了他的观点是正确的。
-
"That's a rather useless test, since it really depends on how well the individual programs have been optimized; I've managed to speed up some of them by 4-6 times or more, making it clear that the comparison between unoptimized programs is rather silly."
这是一个相当无用的测试,因为它实际上取决于单个程序优化的程度;我已经设法将其中一些程序的速度提高了4-6倍或更多,这表明在未优化的程序之间进行比较是相当愚蠢的。
Ask yourself whether the author has actually shown you that he's managed to "speed up some of them by 4-6 times or more" - it's an easy claim to make!
问问你自己,作者是否真的向你展示了他“将其中的一些速度提高了4-6倍或更多”——这是一个很简单的说法!
#16
5
In theory, for long running server-type application, a JIT-compiled language can become much faster than a natively compiled counterpart. Since the JIT compiled language is generally first compiled to a fairly low-level intermediate language, you can do a lot of the high-level optimizations right at compile time anyway. The big advantage comes in that the JIT can continue to recompile sections of code on the fly as it gets more and more data on how the application is being used. It can arrange the most common code-paths to allow branch prediction to succeed as often as possible. It can re-arrange separate code blocks that are often called together to keep them both in the cache. It can spend more effort optimizing inner loops.
从理论上讲,对于长期运行的服务器类型应用程序,jit编译语言可以比本地编译的对等语言快得多。由于JIT编译语言通常首先被编译成一种相当低级的中间语言,因此您可以在编译时进行许多高级优化。最大的优势在于,当JIT获得越来越多关于应用程序使用方式的数据时,它可以动态地重新编译代码的各个部分。它可以安排最常见的代码路径,以便分支预测尽可能成功。它可以重新排列通常被调用的单独的代码块,以将它们保存在缓存中。它可以花费更多的精力来优化内部循环。
I doubt that this is done by .NET or any of the JREs, but it was being researched back when I was in university, so it's not unreasonable to think that these sort of things may find their way into the real world at some point soon.
我怀疑这是由。net或任何JREs完成的,但我在大学的时候就已经研究过了,所以认为这些东西会很快进入现实世界的想法是合理的。
#17
5
For 'embarassingly parallel' problems, when using Intel TBB and OpenMP on C++ I have observed a roughly 10x performance increase compared to similar (pure math) problems done with C# and TPL. SIMD is one area where C# cannot compete, but I also got the impression that TPL has a sizeable overhead.
对于“令人尴尬的并行”问题,当我在c++中使用Intel TBB和OpenMP时,我发现与使用c#和TPL处理的类似(纯数学)问题相比,性能提高了大约10倍。SIMD是c#无法竞争的领域之一,但我也有这样的印象:TPL有相当大的开销。
That said, I only use C++ for performance-critical tasks where I know I will be able to multithread and get results quickly. For everything else, C# (and occasionally F#) is just fine.
也就是说,我只在性能关键的任务中使用c++,因为我知道我可以多线程并快速地得到结果。除此之外,c#(偶尔f#)也很好。
#18
5
It's an extremely vague question without real definitive answers.
这是一个极其模糊的问题,没有确切的答案。
For example; I'd rather play 3D-games that are created in C++ than in C#, because the performance is certainly a lot better. (And I know XNA, etc., but it comes no way near the real thing).
例如;我宁愿玩c++开发的3d游戏,也不愿玩c#,因为性能肯定比c#好得多。(我知道XNA,等等,但它不可能接近真实的东西)。
On the other hand, as previously mentioned; you should develop in a language that lets you do what you want quickly, and then if necessary optimize.
另一方面,如前所述;您应该使用一种语言进行开发,该语言允许您快速地完成所需的工作,然后在必要时进行优化。
#19
4
Applications that require intensive memory access eg. image manipulation are usually better off written in unmanaged environment (C++) than managed (C#). Optimized inner loops with pointer arithmetics are much easier to have control of in C++. In C# you might need to resort to unsafe code to even get near the same performance.
需要密集内存访问的应用程序。在非托管环境(c++)中编写映像操作通常比在托管环境(c#)中编写映像更好。使用指针算法优化的内部循环更容易在c++中进行控制。在c#中,您可能需要使用不安全的代码来接近相同的性能。
#20
4
I've tested vector
in C++ and C# equivalent - List
and simple 2d arrays.
我已经在c++和c#等效列表和简单的2d数组中测试了vector。
I'm using Visual C#/C++ 2010 Express editions. Both projects are simple console applications, I've tested them in standard (no custom settings) release and debug mode. C# lists run faster on my pc, array initialization is also faster in C#, math operations are slower.
我使用的是Visual c# / c++ 2010 Express版本。这两个项目都是简单的控制台应用程序,我已经在标准(没有自定义设置)发布和调试模式中测试了它们。c#列表在我的pc上运行得更快,数组初始化在c#中也更快,数学运算也更慢。
I'm using Intel Core2Duo P8600@2.4GHz, C# - .NET 4.0.
我正在使用Intel Core2Duo P8600@2.4GHz, c# -。net 4.0。
I know that vector implementation is different than C# list, but I just wanted to test collections that I would use to store my objects (and being able to use index accessor).
我知道向量实现与c# list不同,但我只想测试我用来存储对象的集合(以及能够使用索引访问器)。
Of course you need to clear memory (let's say for every use of new
), but I wanted to keep the code simple.
当然,您需要清除内存(假设每次使用new),但我希望代码保持简单。
C++ vector test:
c++向量测试:
static void TestVector()
{
clock_t start,finish;
start=clock();
vector<vector<double>> myList=vector<vector<double>>();
int i=0;
for( i=0; i<500; i++)
{
myList.push_back(vector<double>());
for(int j=0;j<50000;j++)
myList[i].push_back(j+i);
}
finish=clock();
cout<<(finish-start)<<endl;
cout<<(double(finish - start)/CLOCKS_PER_SEC);
}
C# list test:
c#中测试:
private static void TestVector()
{
DateTime t1 = System.DateTime.Now;
List<List<double>> myList = new List<List<double>>();
int i = 0;
for (i = 0; i < 500; i++)
{
myList.Add(new List<double>());
for (int j = 0; j < 50000; j++)
myList[i].Add(j *i);
}
DateTime t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
}
C++ - array:
c++数组:
static void TestArray()
{
cout << "Normal array test:" << endl;
const int rows = 5000;
const int columns = 9000;
clock_t start, finish;
start = clock();
double** arr = new double*[rows];
for (int i = 0; i < rows; i++)
arr[i] = new double[columns];
finish = clock();
cout << (finish - start) << endl;
start = clock();
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arr[i][j] = i * j;
finish = clock();
cout << (finish - start) << endl;
}
C# - array:
c# -数组:
private static void TestArray()
{
const int rows = 5000;
const int columns = 9000;
DateTime t1 = System.DateTime.Now;
double[][] arr = new double[rows][];
for (int i = 0; i < rows; i++)
arr[i] = new double[columns];
DateTime t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
t1 = System.DateTime.Now;
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arr[i][j] = i * j;
t2 = System.DateTime.Now;
Console.WriteLine(t2 - t1);
}
Time: (Release/Debug)
时间:(发布/调试)
C++
c++
- 600 / 606 ms array init,
- 600 / 606 ms数组init,
- 200 / 270 ms array fill,
- 200 / 270 ms阵列填充,
- 1sec /13sec vector init & fill.
- 1秒/13秒的矢量初始化和填充。
(Yes, 13 seconds, I always have problems with lists/vectors in debug mode.)
(是的,13秒,我总是在调试模式下遇到列表/向量的问题。)
C#:
c#:
- 20 / 20 ms array init,
- 20 ms数组init,
- 403 / 440 ms array fill,
- 403 / 440 ms阵列填充,
- 710 / 742 ms list init & fill.
- 710 / 742 ms列表初始化和填充。
#21
3
Well, it depends. If the byte-code is translated into machine-code (and not just JIT) (I mean if you execute the program) and if your program uses many allocations/deallocations it could be faster because the GC algorithm just need one pass (theoretically) through the whole memory once, but normal malloc/realloc/free C/C++ calls causes an overhead on every call (call-overhead, data-structure overhead, cache misses ;) ).
这得视情况而定。如果字节码转换成机器码(而不仅仅是JIT)(我的意思是如果你执行程序),如果您的程序使用了很多分配/回收它可以更快,因为GC算法只需要一个(理论上)穿过整个内存一次,但正常malloc / realloc /免费的C / c++电话导致的开销每个调用(调用开销,数据结构开销,缓存缺失;))。
So it is theoretically possible (also for other GC languages).
因此,这在理论上是可能的(对于其他GC语言也是如此)。
I don't really see the extreme disadvantage of not to be able to use metaprogramming with C# for the most applications, because the most programmers don't use it anyway.
我并没有真正看到不能在大多数应用程序中使用c#编程的极端缺点,因为大多数程序员都不使用它。
Another big advantage is that the SQL, like the LINQ "extension", provides opportunities for the compiler to optimize calls to databases (in other words, the compiler could compile the whole LINQ to one "blob" binary where the called functions are inlined or for your use optimized, but I'm speculating here).
另一个很大的优点是,SQL,如LINQ“扩展”,为编译器优化对数据库的调用提供了机会(换句话说,编译器可以将整个LINQ编译为一个“blob”二进制,其中所调用的函数是内联的,或者为您的使用进行优化,但是我在这里)。
#22
2
I suppose there are applications written in C# running fast, as well as there are more C++ written apps running fast (well C++ just older... and take UNIX too...)
- the question indeed is - what is that thing, users and developers are complaining about ...
Well, IMHO, in case of C# we have very comfort UI, very nice hierarchy of libraries, and whole interface system of CLI. In case of C++ we have templates, ATL, COM, MFC and whole shebang of alreadyc written and running code like OpenGL, DirectX and so on... Developers complains of indeterminably risen GC calls in case of C# (means program runs fast, and in one second - bang! it's stuck).
To write code in C# very simple and fast (not to forget that also increase chance of errors. In case of C++, developers complains of memory leaks, - means crushes, calls between DLLs, as well as of "DLL hell" - problem with support and replacement libraries by newer ones...
I think more skill you'll have in the programming language, the more quality (and speed) will characterize your software.
我猜想有一些用c#编写的应用程序运行得很快,也有更多c++编写的应用程序运行得很快(好吧,c++只是更老了……)问题是,用户和开发人员在抱怨什么呢?嗯,IMHO,对于c#,我们有非常舒适的UI,非常好的库层次结构,以及CLI的整个界面系统。对于c++,我们有模板、ATL、COM、MFC和完整的已经编写和运行的代码,比如OpenGL、DirectX等等……开发人员抱怨在c#(意味着程序运行得很快,并且在一秒钟内——砰!这是卡)。用c#编写代码非常简单和快速(不要忘记这也增加了出错的几率。在c++的情况下,开发人员抱怨内存泄漏,-意味着crush, DLL之间的调用,以及“DLL hell”——新版本的支持和替换库的问题……我认为你在编程语言中掌握的技能越多,你的软件就越有质量(和速度)。
#23
2
I would put it this way: programmers who write faster code, are the ones who are the more informed of what makes current machines go fast, and incidentally they are also the ones who use an appropriate tool that allows for precise low-level and deterministic optimisation techniques. For these reasons, these people are the ones who use C/C++ rather than C#. I would go as far as stating this as a fact.
我是这样说的:编写速度更快的代码的程序员更了解是什么使当前的机器运行得更快,顺便说一句,他们也使用合适的工具,允许精确的低层次和确定性优化技术。由于这些原因,这些人使用的是C/ c++而不是c#。我甚至认为这是事实。
#24
2
If I'm not mistaken, C# templates are determined at runtime. This must be slower than compile time templates of C++.
如果我没弄错的话,c#模板是在运行时确定的。这必须比c++的编译时模板慢。
And when you take in all the other compile-time optimizations mentioned by so many others, as well as the lack of safety that does, indeed, mean more speed...
当你考虑到其他许多人提到的所有编译时优化,以及安全性的缺乏,确实意味着更高的速度……
I'd say C++ is the obvious choice in terms of raw speed and minimum memory consumption. But this also translates into more time developing the code and ensuring you aren't leaking memory or causing any null pointer exceptions.
从原始速度和最小内存消耗来看,c++是显而易见的选择。但这也意味着要花更多时间开发代码,并确保不会泄漏内存或导致任何空指针异常。
Verdict:
结论:
-
C#: Faster development, slower run
更快的开发,更慢的运行
-
C++: Slow development, faster run.
c++:开发速度慢,运行速度快。
#25
1
> After all, the answers have to be somewhere, haven't they? :)
毕竟,答案一定在某个地方,不是吗?:)
Umm, no.
嗯,没有。
As several replies noted, the question is under-specified in ways that invite questions in response, not answers. To take just one way:
正如一些答复所指出的,这个问题没有得到充分的说明,而是以提问的方式来回答,而不是回答。就这么简单:
- the question conflates language with language implementation - this C program is both 2,194 times slower and 1.17 times faster than this C# program - we would have to ask you: Which language implementations?
- 这个问题将语言和语言实现混为一谈——这个C程序比这个c#程序慢2194倍,快1.17倍——我们不得不问你:哪种语言实现?
And then which programs? Which machine? Which OS? Which data set?
然后哪个项目?哪个机器?哪些操作系统?数据集?
#26
0
It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.
这真的取决于你想在你的代码中完成什么。我听说VB的性能有什么不同,这只是一个都市传说。NET、c#和托管c++。然而,我发现,至少在字符串比较中,托管c++击败了c#, c#反过来又击败了VB.NET。
I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.
我并没有对语言之间的算法复杂性做过任何详尽的比较。我还在每种语言中使用默认设置。在VB。NET我正在使用设置来要求声明变量,等等。这是我在托管c++中使用的代码(正如您所看到的,这段代码非常简单)。在Visual Studio 2013中,我使用。net 4.6.2运行了相同的其他语言。
#include "stdafx.h"
using namespace System;
using namespace System::Diagnostics;
bool EqualMe(String^ first, String^ second)
{
return first->Equals(second);
}
int main(array<String ^> ^args)
{
Stopwatch^ sw = gcnew Stopwatch();
sw->Start();
for (int i = 0; i < 100000; i++)
{
EqualMe(L"one", L"two");
}
sw->Stop();
Console::WriteLine(sw->ElapsedTicks);
return 0;
}
#27
-10
Inspired by this, I did a quick test with 60 percent of common instruction needed in most of the programs.
受此启发,我做了一个快速测试,在大多数程序中需要60%的常用指令。
Here’s the C# code:
这里的c#代码:
for (int i=0; i<1000; i++)
{
StreamReader str = new StreamReader("file.csv");
StreamWriter stw = new StreamWriter("examp.csv");
string strL = "";
while((strL = str.ReadLine()) != null)
{
ArrayList al = new ArrayList();
string[] strline = strL.Split(',');
al.AddRange(strline);
foreach(string str1 in strline)
{
stw.Write(str1 + ",");
}
stw.Write("\n");
}
str.Close();
stw.Close();
}
String array and arraylist are used purposely to include those instructions.
字符串数组和arraylist被故意用于包含这些指令。
Here's the c++ code:
这里的c++代码:
for (int i = 0; i<1000; i++)
{
std::fstream file("file.csv", ios::in);
if (!file.is_open())
{
std::cout << "File not found!\n";
return 1;
}
ofstream myfile;
myfile.open ("example.txt");
std::string csvLine;
while (std::getline(file, csvLine))
{
std::istringstream csvStream(csvLine);
std::vector csvColumn;
std::string csvElement;
while( std::getline(csvStream, csvElement, ‘,’) )
{
csvColumn.push_back(csvElement);
}
for (std::vector::iterator j = csvColumn.begin(); j != csvColumn.end(); ++j)
{
myfile << *j << ", ";
}
csvColumn.clear();
csvElement.clear();
csvLine.clear();
myfile << "\n";
}
myfile.close();
file.close();
}
The input file size I used was 40 KB.
我使用的输入文件大小是40kb。
And here's the result -
这是结果-
- C++ code ran in 9 seconds.
- c++代码在9秒内运行。
- C# code: 4 seconds!!!
- c#代码:4秒! ! !
Oh, but this was on Linux... With C# running on Mono... And C++ with g++.
哦,但是这是在Linux上……c#运行在Mono上…与g和C + + + +。
OK, this is what I got on Windows – Visual Studio 2003:
这是我在Windows - Visual Studio 2003上看到的
- C# code ran in 9 seconds.
- c#代码在9秒内运行。
- C++ code – horrible 370 seconds!!!
- c++代码-可怕的370秒!!