概要:以前上学总听说不同编程语言在运行效率上存在明显差异,我印象中的是C/C++是最快的,python脚本语言是比较慢的。我也不知道说的是不是真的,我们来实践检验真理。
测试内容:为了公平比较 Python、C++ 和 C# 三种语言的运行效率测试。需要在三种语言中实现完全相同的算法,并保证输入数据、算法逻辑、循环次数等参数都一致。通常可以选择一个简单但运算量较大的任务,累加 1 到 100000000。
一、python语言
1.运行代码
import time
total = 0
start = time.time() # 获取起始时间,单位秒
for i in range(0, 100000000):
total += i
end = time.time() # 获取结束时间
elapsed_ms = (end - start) * 1000 # 转换为毫秒
print("Python: 累加结果 =", total)
print("Python: 耗时 =", elapsed_ms, "ms")
2.运行结果
二、C#语言
1.运行代码
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
long total = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 1; i <= 100000000 - 1; i++)
{
total += i;
}
sw.Stop();
Console.WriteLine("C#: 累加结果 = " + total);
Console.WriteLine("C#: 耗时 = " + sw.ElapsedMilliseconds + " ms");
Console.ReadKey();
}
}
2.运行结果
三、C++语言
1.运行代码
#include <iostream>
#include <chrono>
int main() {
long long total = 0;
auto startTime = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= 100000000-1; i++) {
total += i;
}
auto endTime = std::chrono::high_resolution_clock::now();
auto runTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
std::cout << "C++: 累加结果 = " << total << std::endl;
std::cout << "C++: 耗时 = " << runTime << " ms" << std::endl;
return 0;
}
2.运行结果
四、总结
运行耗时结果: C++(49ms) < C#(96ms) < python (10993ms)
三种编程语言运行结果都是一样的,4999999950000000,运行耗时不一样。 果然C++才是YYDS ,感兴趣的可以把程序拷贝回去试试。我的CPU是17-12700H,不同的运行环境 运行的结果回不一样。
有人问:为什么没有别的编程语言,例如Java、JavaScript、Go、R
我回答:我只会这三种语言C++、C#、python ,别的编程语言我不会,也没有开发环境。会的小伙伴可以试试,在评论留下你运行的答案 作为参考。