C++/Go/Lua 效率对比——简单算术运算

测试 sum = sum + i * i 循环1亿次

为什么不是单纯的加法呢,因为发现当i到一定程度的时候,c++的计算时间都是0,可能使用了 优化 sum =(i+1)*i/2

等有空分析c++汇编代码

减少c++的另类优化,所以用的加 i * i,公平起见

1. lua代码

#!/usr/bin/lua

require("os")

local starttime = os.clock()

local length = 100000000

local sum = 0

for i = 1, length do

    sum = sum + i * i

end

print("sum = ", sum)

local endtime = os.clock()

print(string.format("cost time : %.4f", endtime - starttime))

cost time : 1.4200

cost time : 1.4400

cost time : 1.4200

cost time : 1.4600

cost time : 1.4300

平均时间 7.17/6 = 1.434


2.cpp

test.cpp

#include <stdio.h>

#include <time.h>

void test_add(unsigned int length)

{

    unsigned long long sum = 0;

    for(long i=1;i<length; ++i)

        sum += i*i;

    printf("sum = %lu\n", sum);

}

class CalcTime

{

    public:

        CalcTime()

        {

            m_start = clock();

        }

        ~CalcTime()

        {

            unsigned long long end = clock();

            printf("cost time = %f\n", ((double)(end - m_start))/CLOCKS_PER_SEC);

        }

    private:

        unsigned long long m_start = 0;

};

int main()

{

    printf("CLOCKS_PER_SEC = %d\n", CLOCKS_PER_SEC);

    {

        CalcTime calc;

        test_add(100000000);

    }

    return 0;

}

Makefile

test: test.cpp

    g++ -g -O2 --std=c++11 test.cpp -o test

clean:

    rm test


cost time = 0.050000

cost time = 0.050000

cost time = 0.050000

cost time = 0.060000

cost time = 0.050000

平均时间 0.052

3. Go

test_go.go

package main

import "time"

import "fmt"

func test_add(len uint) {

    var sum uint64 = 0

    var i uint = 1

    for ; i < len; i++ {

        sum += (uint64)(i * i)

    }

    fmt.Printf("sum = %v\n", sum)

}

func main() {

    start := time.Now()

    test_add(100000000)

    end := time.Now()

    dif := end.Sub(start)

    fmt.Printf("cost time: %v\n", dif)

}


cost time: 56.804357ms

cost time: 57.604325ms

cost time: 57.030147ms

cost time: 55.54873ms

cost time: 58.058417ms

平均时间=56.98ms


结论:

C++ / Go /Lua 效率对比

52 :56.98 :1434

1:1.0958:27.5769

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。