サムネがコーヒーの記事は書きかけです。

素数生成によるC++,Java,Python3の実行速度比較

C++,Java,Python3で10000番目の素数生成を行なって実行速度を比較してみます。

Python

import numpy as np
import time 

class Prime:
    def __init__(self,n) -> None:
        self.n = n
        pass

    def calcNth(self):
        currN = 1
        i = 1
        while self.n > currN:
            i += 1
            if self.isPrime(i):
                currN += 1
        return i
       
    def isPrime(self,n):
        i = 1
        while i < np.sqrt(n):
            i += 1  
            if n%i == 0:
                return False
        return True

t0 = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
p = Prime(10000)
print(p.calcNth())
print(time.clock_gettime_ns(time.CLOCK_MONOTONIC)-t0)

>>>
104729
3453106000

Java

public class Prime {
    
    int n;

    public Prime(int n){
        this.n = n;
    }

    public boolean isPrime(int n){
        int i = 1;
        while (i < Math.sqrt(n)){
            i += 1;
            if (n%i == 0){
                return false;
            }
    
        }
    return true;
    }

    public int calcNth(){
        int currN = 1;
        int i = 1;
        while (n > currN){
            i++;
            if (isPrime(i)){
                currN ++;
            }
        }
        return i;
    }

    public static void main(String[] args) {
        double t0 = System.nanoTime();
        Prime p = new Prime(10000);
        System.out.println(p.calcNth());
        System.out.println(System.nanoTime() - t0);
    }
}

>>>
104729
4988583.0

C++

#include <iostream>
#include <string>
#include<math.h>
#include <time.h>
using namespace std;

class Prime
{
private:
    int n;

public:
    Prime(int n){
        this->n = n;
    }
    bool isPrime(int n){
        
        for (int i = 2; i <= sqrt(n); i++){
            if (n%i == 0){
                return false;
            }
        }
        return true;
    }
    void calcNth(){
        int currN = 0;
        int i = 1;
        while (this->n > currN){
            i++;
            if (isPrime(i)){
                currN ++;
            }
        }
        cout<<i<<endl;
    }
};

int main(){
    struct timespec t0;
    struct timespec t1;
    clock_gettime(CLOCK_REALTIME, &t0); 
    Prime p(10000);
    p.calcNth();
    clock_gettime(CLOCK_REALTIME, &t1);
    cout<<(t1.tv_nsec -t0.tv_nsec)<<endl;

};

>>>
104729
12802000

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です