I wrote a program in both C++ and Java to print "Hello World" 100,000 times, but I noticed that the C++ code takes too long compared to the Java code; The Java code takes about 6 seconds averagely and the C++ code takes about 18 seconds averagely, both run from the command line; Can someone please explain why, thanks.
The name of the program is first.java and first.cpp for Java and C++ respectively I used: java first.java
; and first.exe
; both from the command line
g++ --version g++ (Rev6, Built by MSYS2 project) 11.2.0
java --version java 13.0.2, 2020-01-14
Java Code
class first {
public static void main(String... args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
System.out.println("Hello World");
}
long end = System.currentTimeMillis();
long dur = end - start;
System.out.println(dur / 1000);
}
}
C++ Code
#include <iostream>
#include <string>
#include <chrono>
using namespace std;
int main()
{
auto start = std::chrono::system_clock::now();
for (int i = 0; i < 100000; i++)
{
cout << "Hello World" << endl;
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
cout << elapsed_seconds.count() << endl;
}
Aucun commentaire:
Enregistrer un commentaire