C,D,Go,Rust,Nim,Zig,V,Julia,Py,C#,Kotlin 11语回文数大战!仅供娱乐参考!

原来写在开源中国的!早期的5语升级版!
https://my.oschina.net/raddleoj/blog/510932

娱乐!娱乐!请不要诋毁任何语言!!!!
我有个心愿!用汇编写一个!当年大学时没好好学汇编!惭愧!正在看汇编!
20200820 加入Kotlin语言,就不加java了。
20200817 加入 c# 版本!另外D语言改了release编译没有什么变化;
20200816加入Julia和py版本!
20200815加入Vlang语言版本!
20200814加入zig语言的版本!
20171123 rust改用release编译且换官方时间库release编译后执行速度惊人;
20160829Nim改releas编译;
20160712]Rust 1.10MSVC编译;
20160527Rust1.9MSVC编译;
20160416rust1.8ms编译;
20160307改用rust1.7(ms)重编译了;
加了个D语言(C的代码就改了时间部分就移植了);
20160131在树莓派兼容的香蕉派m1上编译的go1.5测试;
20160127 Nim 0.13;
20160127测试Rust 1.6 MSVC;
20151214测试了Rust 1.5 GCC版;
20151102测试了nim0.12;
20151030测试了Rust 1.4;

-----------------------------------------------
联想笔记本 inter i7,2.4GHz,16G,win10
C语言(应该是全C,vs2015编译)

#include
#include
#include
bool ishuiwen(int n) {
    int sn = 0;
    sn = n;
    int tn = 0;
    while (sn != 0) {
        tn = tn * 10 + sn % 10;
        sn = sn / 10;
    }
    if (tn == n)
        return true;
    return false;
}
int hw1() {
    int tx = 0;
    int x = 0;
    for (x = 0; x <= 10000000; x++) {
        if (ishuiwen(x) == true)
            tx ++;
    }
    return tx;
}

void runhw() {
    clock_t start, finish;
    double  duration;
    start = clock();
    int total = hw1();
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;
    printf("total = %d,  %f seconds\n", total, duration);
}

1100毫秒+(相信c的潜力没发挥出来)

20200815 用vs2019 release 模式编译后 输出:total = 10999, 0.126000 seconds,c的威力出来了!

---------------------------

DLang(在vs中用D插件编译的)

import std.stdio;
import std.datetime;

bool ishuiwen(int n) {
    int sn = 0;
    sn = n;
    int tn = 0;
    while (sn != 0) {
        tn = tn * 10 + sn % 10;
        sn = sn / 10;
    }
    if (tn == n)
        return true;
    return false;
}
int hw1() {
    int tx = 0;
    int x = 0;
    for (x = 0; x <= 10000000; ++x) {
        if (ishuiwen(x) == true)
            tx ++;
    }
    return tx;
}

int main(string[] argv)
{
    auto currentTime1 = Clock.currTime();
    auto all = hw1();
    auto currentTime2 = Clock.currTime();
    writeln("it is ", all, "have ", currentTime2 - currentTime1, " sec.");
    return 0;
}

764毫秒左右。D 2.07编译的

---------------------------

Go

func HW(num int) bool {
    var source int = num
    var tnum int = 0
    for num != 0 {
        tnum = tnum*10 + num%10
        num = num / 10
    }
    if tnum == source {
        //fmt.Println(source)
        return true
    }
    return false
}
func hw() {
    all := 10000000
    t1 := time.Now()
    total := 0
    for n := 0; n <= all; n++ {
        if HW(n) {
            total++
        }
    }
    t2 := time.Now()
    fmt.Println(total)
    fmt.Println(t2.Sub(t1))
}

Go 1.5.1    200毫秒+;

Go 1.5.2    209毫秒+;

香蕉派m1上,Go1.5,2.5秒左右;

----------------

Rust

use std::time::SystemTime;

fn main() {
    hw21();
}

fn hw21(){
    let local1 = SystemTime::now();
    hw2();
    let local2 = SystemTime::now();
    let rtime = local2.duration_since(local1);
    println!("{:?}", rtime);
}

fn hw2(){
    let mut tx:i32 = 0;
    for x in 0..10000000 {
        if hw(x) == true {
            tx=tx+1;
        }
    }
    println!("--{:?}--", tx);
}

fn hw(n: i32) -> bool {
    let mut sn:i32 = n;
    let mut tn:i32 = 0;
    while sn != 0 {
        tn = tn*10 + sn%10;
        sn = sn/10;
    }
    if tn == n {
        return true;
    }
    return false;
}

Rust 1.3  900毫秒+

Rust 1.4 同一套代码,用时飙到了1100毫以上。最高的1500多毫秒!

Rust 1.5 GCC 同一套代码,用时927毫秒! MSVC版的 Rust 1.5 没有编译成功!

Rust 1.6 MSVC版 959 毫秒+,数次平均970毫秒左右

Rust 1.7 MSVC版本 967毫秒,不是特别稳定,96X毫秒-1秒100毫秒不等。【20160307】

Rust 1.8 MSVC版本 95X 毫秒,比较稳定,95X毫秒-96X毫秒不等。【20160416】每次不要覆盖安装rust新版,卸载以前的安装,不然编译很容易出错!

Rust1.9 MSVC 1秒多,比1.8退步了。但是这不代表Rust退步了。请诸位各自明辨!

Rust1.10 MSVC 1秒多。根据某个评论用户的测试其运行大约都是220毫秒左右,所以最后执行效率可能因为各种因素而不通。

20171123 这次使用了 cargo build --release 编译,还升级了时间计算,用的rust自带的原生std::time。120毫秒上下。果然不负rust的称号!

PS E:\rustprojects\rusttest> ./rust_test --10999-- Duration { secs: 1, nanos: 78146300 } // 上面是以前的 // 下面是带有release编译的,基本120-130毫秒之间,但是用的硬件稍有改动:

i5 4460 3.2g 4核+8G+win10

F:\work\rustp\rustp02>target\release\rustp02.exe --10999-- Ok(Duration { secs: 0, nanos: 120095200 })

-----------------

Nim 0.11.2

import strutils, times

proc ishuiwen(n : int): bool =
  var sn : int
  sn = n
  var tn : int
  tn = 0
  while sn != 0 :
    tn = tn * 10 + sn mod 10
    sn = sn div 10
  if tn == n :
    return true
  return false

proc hw1() : int =
  var tx:int = 0
  for x in 0..10000000 :
    if ishuiwen(x) == true :
      tx=tx+1
  return tx

var t0 = times.cpuTime()
var total : int = hw1()
var t1 = times.cpuTime()
echo("Nim HW all ok ", total, " . use : ", t1 - t0)

4000毫秒+

20151102更新了Nim 0.12版,测试回文数计算速度有提高,2.8-2.9秒;

20160127  Nim 0.13  2.7秒多点;

20160829,在某个网友提示下加入-d:release编译,性能提升。200多毫秒。感谢那位提示的网友。

-----------------------------------------------------------

zig 版本 20200814

const print = std.debug.print;
const std = @import("std");
const os = std.os;
const time = std.time;

fn ishuiwen(n: i32) bool {
    var sn: i32 = 0;
    sn = n;
    var tn: i32 = 0;
    while (sn != 0) {
        tn = tn * 10 + @mod(sn, 10);
        sn = @divTrunc(sn, 10);
    }
    if (tn == n) {
        //print("数::{} == 回文数::{}\n", .{ tn, n });
        return true;
    }
    return false;
}

fn hw1() i32 {
    var tx: i32 = 0;
    var x: i32 = 0;
    var i: i32 = 0;
    var max: i32 = 10000000;
    while (i < max) : (i += 1) {
        if (ishuiwen(i) == true) {
            tx += 1;
            //print("{}\n", .{i});
        }
    }
    return tx;
}

fn runhw() void {
    var s: i64 = time.milliTimestamp();
    var r: i32 = hw1();
    var e: i64 = time.milliTimestamp();
    var ss: i64 = e - s;
    print("Hello, {} == result::{} -- start::{} -- end::{} -- time::{}!\n", .{ "world", r, s, e, ss });
}

pub fn main() !void {
    runhw();
    const stdout = std.io.getStdOut().writer();
    try stdout.print("Hello, {}!\n", .{"world"});
    try stdout.print("Hello[{}]!\n", .{@mod(12, 10)});
    try stdout.print("Hello[{}]!\n", .{@divTrunc(12, 10)});
}

clear; zig fmt .\huiwen.zig;zig build-exe --release-fast .\huiwen.zig; .\huiwen.exe

Hello, world == result::10999 -- start::1597487195088 -- end::1597487195237 -- time::149!

也非常不错 和rust非常接近!

-----------------------------------------

Vlang V语言

module main

import time

fn main() {
    sw := time.new_stopwatch({})
    r := huiwen()
    println('hello world VLang is here Res=$r == tme::${sw.elapsed().milliseconds()}ms')
}

fn huiwen() int {
    mut tx := 0
    for i in 0..10000000 {
        if ishuiwen(i) == true {
            tx ++
        }
    }
    return tx
}

fn ishuiwen(n int) bool {
    mut sn := 0
    sn = n
    mut tn := 0
    for sn != 0 {
        tn = tn * 10 + sn % 10
        sn = sn / 10
    }
    if tn == n {
        return true
    }
    return false
}

// 编译运行命令 v run .\vexe001.v; v version

hello world VLang is here Res=10999 == tme::339ms
V 0.1.28 bbaf6e3
----------------------------------------
julia 20200816 成都今天下雨
//貌似julia要先安装包
import Pkg; Pkg.add("Dates") # 这是标准库的居然要安装!
 

using Dates
using Printf

"""
是否回文
"""
function ishuiwen(n::Int64)
    sn::Int32 = 0 # 可以不用类型
    sn = n
    tn::Int32 = 0
    while sn != 0
        tn = tn * 10 + sn % 10
        sn = sn ÷ 10
    end
    if tn == n
        return true
    end
    return false
end

"""
回文10000000
"""
function huiwen(max::Int64=10000000)
    tx::Int32 = 0
    x::Int32 = 0
    for i = 0:max
        if ishuiwen(i) == true
            tx+=1
        end
    end
    return tx
end

function run()
    t1 = now()
    r = huiwen(10000000)
    t2 = now()
    tx = t2 - t1
    @printf("回文 结果:: %d == 时间:: %F \n", r, Dates.value(tx))
end

run()
# julia .\huiwen.jl; julia --version

回文 结果:: 10999 == 时间:: 240.000000
julia version 1.5.0
---------------------------------------
python 20200816

# coding=utf-8
""" 回文数 """

import datetime
from numba import jit

"""
是否回文
"""
@jit
def ishuiwen(n:int):
    sn = 0 # 可以不用类型
    sn = n
    tn = 0
    while sn != 0:
        tn = tn * 10 + sn % 10
        sn = sn // 10
    if tn == n:
        return True
    return False

"""
回文10000000
"""
@jit
def huiwen(max:int=10000000):
    tx = 0
    for i in range(0, max):
        # print(f"数:{i}")
        if ishuiwen(i):
            tx+=1
            # print(f"回文数:{i}")
    return tx

def run():
    t1 = datetime.datetime.now()
    r = huiwen()
    t2 = datetime.datetime.now()
    tx = (t2 - t1)
    print(f"回文 结果:: {r} == 时间::[{tx.seconds}]秒{tx.microseconds/1000}毫秒")


if __name__ == '__main__':
    run()
# python .\huiwen.py;python --version

回文 结果:: 10999 == 时间::[13]秒959.858毫秒   加jit前 13-14秒
加 jit 后:回文 结果:: 10999 == 时间::[0]秒579.826毫秒
Python 3.8.4
---------------------------------------
C# 20200817,core 3.1,win,release编译
 

// C# 20200817 release 模式
        static bool ishuiwen(int n)
        {
            int sn = 0;
            int tn = 0;
            sn = n;
            while (sn != 0)
            {
                tn = tn * 10 + sn % 10;
                sn = sn / 10;
            }
            if (tn == n)
                return true;
            return false;
        }
        static int hw1(int max = 10000000)
        {
            int tx = 0;
            int x = 0;
            for (x = 0; x <= max; x++)
            {
                if (ishuiwen(x) == true)
                    tx++;
            }
            return tx;
        }
        static void runhw()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            int total = hw1();
            watch.Stop();
            Console.WriteLine($"--{total}-- In milliseconds: {watch.ElapsedMilliseconds}");
        }

--10999-- In milliseconds: 133,c#成绩不赖!
---------------------------------------
Kotlin 20202820

// huiwen.kt
import kotlin.system.*

fun main(args: Array) {
    run()
    println("Hello, World!")
}

fun ishuiwen(n: Int) : Boolean{
    var sn: Int = n;
    var tn: Int = 0;
    while (sn != 0) {
        tn = tn * 10 + sn % 10;
        sn /= 10;
    }
    if (tn == n) {
        return true;
    }
    return false;
}

fun huiwen(max: Int = 10000000) : Int{
    var tx: Int = 0;
    for (x: Int in 0..max) {
        if (ishuiwen(x))
            tx ++;
    }
    return tx;
}

fun run(){
    var total: Int = 0
    val t1 = getTimeMillis()
    val total: Int = huiwen(10000000);
    val t2 = getTimeMillis()
    val tms = t2 - t1
    println("Result:: $total -- Time:: $tms ")
}

// kotlinc huiwen.kt -o huiwen;kotlinc -version;.\huiwen.exe

info: kotlinc-native 1.4.0-rc-308 (JRE 1.8.0_241-b07)
Kotlin/Native: 1.4
Result:: 10999 -- Time:: 221  //java应该也是一个水平就不写java的了

=======================

我可不是想说谁好谁坏!!

我不是某语言拥护者。反正需要不断进步!

你可能感兴趣的:(技术和学习,技术娱乐,编程语言,go,rust,kotlin,c#)