Why in simple for loop the same code in Java works 4 times faster than in C++? i.e. in Java this code completes in 700-800 ms and in C++ 4-5 SECONDS. Although C++ usually considered much faster than Java, especially with CPU-bound workloads. Have i lost sight of some important moment ???
Java:
import java.time.Duration;
import java.time.Instant;
public class Main {
public static void main(String[] args) {
long x = 0;
Instant start = Instant.now();
for (long i = 0; i < 2147483647; i++)
x += i;
Instant end = Instant.now();
Duration result = Duration.between(start, end);
System.out.println("TIME: " + result.toMillis());
System.out.println("X = " + x);
}
}
Output:
TIME: 799
X = 2305843005992468481
C++:
#include <iostream>
#include <ctime>
int main()
{
long long x = 0;
clock_t begin = clock();
for (long long i = 0; i < 2147483647; i++)
x += i;
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "Time elapsed: " << elapsed_secs << std::endl;
std::cout << "x = " << x << std::endl;
return 0;
}
Output:
Time elapsed: 4.59629
x = 2305843005992468481