Question

In: Computer Science

Compare C++ speed to Python speed. To compare Execution Time of: c++ vs. Py : //...

Compare C++ speed to Python speed.


To compare Execution Time of: c++ vs. Py :
// this is c++ code // covert this code to python and compare their execution time

#include<time.h>
#include <iostream>
using namespace std;
#include <chrono> //for time
using namespace std::chrono;

void doSomething() //to insert any execution code here to measure its running time
{ int x=6795; // cout << "Enter 4-digit integer x ?\n"; cin >> x;
for (int i = 1000; i < 2000000; i++) //a constant number of iterations
{
if (i % 2) x = i + int(sqrt(x)); else x = i + x * x; //do any computation here
}
}

void computeTime()
{ auto start = high_resolution_clock::now(); //starting time in milli-seconds
doSomething();
auto stop = high_resolution_clock::now(); //stopping time in milli-seconds
auto duration = duration_cast<microseconds>(stop - start); //duration time in milli-seconds
cout << "duration= " << duration.count() << endl;
}

void main()
{
int more = 1;
while (more) { computeTime(); cout << "more? <0,1> "; cin >> more; }
system("pause");
}

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

// ( Python version. Be careful to put correct indentation for Python code below)

#---------- Now Python code to do the same as above code in C++
import math
import datetime

def measureSpeed():

t1 = datetime.datetime.now().microsecond

x = 6795 # cout << "Enter 4-digit integer x ?\n"; cin >> x;
#for (int i = 1000; i < 2000000; i++) //a constant number of iterations
for i in range(1000,2000000,1):
if (i % 2):
x = i + math.sqrt(x) #x = i + int(sqrt(x));
else:
x = i + x * x #do any computation here

t2 = datetime.datetime.now().microsecond

print(t2)
print(t1)
print(t2-t1)


def main():
more=1
while(more):
more = input("Please enter <0 or 1> to stop or continue:\n")
print(f'You entered {more}')
if(more):
measureSpeed()

main()

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

Solutions

Expert Solution

ANSWER:

  • I have provided the properly commented  and indented code so you can easily copy the code as well as check for correct indentation.
  • I have provided the output image of the code so you can easily cross-check for the correct output of the code.
  • Have a nice and healthy day!!

CODE

  • C++11 CODE
#include<time.h>
#include <iostream>
#include <cmath>
using namespace std;
#include <chrono> //for time
using namespace std::chrono;

void doSomething() //to insert any execution code here to measure its running time
{ 
        int x=6795; // cout << "Enter 4-digit integer x ?\n"; cin >> x;
        for (int i = 1000; i < 2000000; i++) //a constant number of iterations
        {
                if (i % 2) 
                        x = i + int(sqrt(x));
                else
                        x = i + x * x; //do any computation here
        }
}

void computeTime()
{ 
        auto start = high_resolution_clock::now(); //starting time in milli-seconds
        doSomething();
        auto stop = high_resolution_clock::now(); //stopping time in milli-seconds
        auto duration = duration_cast<microseconds>(stop - start); //duration time in milli-seconds
        cout << "duration= " << duration.count() <<" Microseconds" << endl;
}

int main()
{
        int more = 1;
        while (more)
        { 
                computeTime();
                cout << "more? <0,1> ";
                cin >> more;
        }
        system("pause");
}
  • PYTHON CODE
import math
import datetime

def measureSpeed():
    # starting time, using datetime.datetime.now()
    t1 = datetime.datetime.now()
    
    # required code
    x = 6795 # cout << "Enter 4-digit integer x ?\n"; cin >> x;for (int i = 1000; i < 2000000; i++) //a constant number of iterations
    for i in range(1000,2000000,1):
        if (i % 2):
            x = i + math.sqrt(x) #x = i + int(sqrt(x));
        else:
            x = i + x * x #do any computation here
    # end time        
    t2 = datetime.datetime.now()
    
    # calculating duration, in seconds using total_seconds method of timedelta
    duration = (t2-t1).total_seconds()
    # converting seconds to microseconds
    durationMS = duration * (10**6)
    
    # displaying results
    print("duration = {:d} Microseconds".format(int(durationMS)))

# main function
def main():
    more=1
    # while loop, till more is 1
    while(more):
        # calling function measureSpeed
        measureSpeed()
        # prompting user, and converting input to integer using int function
        more = int(input("Please enter <0 or 1> to stop or continue:\n"))

# calling main
main()

OUTPUT IMAGE

  • C++ OUTPUT

  • Python OUTPUT


Related Solutions

What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are at least 40 lines of comments and 40 lines of code (1 point) b) the problem is described at the top of the program in a readable fashion (1 point) c) the code includes at least one instance of each of the five learning objectives listed above. (3 points) d) the code solves the problem. This may be assessed in part by a 'code...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are at least 40 lines of comments and 40 lines of code (1 point) b) the problem is described at the top of the program in a readable fashion (1 point) c) the code includes at least one instance of each of the five learning objectives listed above. (3 points) d) the code solves the problem. This may be assessed in part by a 'code...
Java, Python, and C++ are three of the most useful programming languages to learn. Compare the...
Java, Python, and C++ are three of the most useful programming languages to learn. Compare the functionalities of all three programming languages. Why would you choose one language over another? Provide code examples demonstrating their usefulness in a real-world scenario.
Draw a position-vs-time, velocity-vs-time, and acceleration-vs-time graph for each of the following objects: 1. A car...
Draw a position-vs-time, velocity-vs-time, and acceleration-vs-time graph for each of the following objects: 1. A car traveling in a straight line at a constant speed. 2. A ball rolling down a hill, getting faster as time goes by. 3. A rock that is tossed straight up in the air before coming back down to its starting point.
Assignment Requirements Write a python application that consists of two .py files. One file is a...
Assignment Requirements Write a python application that consists of two .py files. One file is a module that contains functions used by the main program. NOTE: Please name your module file: asgn4_module.py The first function that is defined in the module is named is_field_blank and it receives a string and checks to see whether or not it is blank. If so, it returns True, if not it return false. The second function that is defined in the module is named...
Compare the following pairs of methods/techniques: Time stamping vs. optimistic methods in distributed systems
Compare the following pairs of methods/techniques: Time stamping vs. optimistic methods in distributed systems
Compare the execution times of the three equivalent R commands (a) y=c();for (t in 1:Nsim) y[t]=sin(t)...
Compare the execution times of the three equivalent R commands (a) y=c();for (t in 1:Nsim) y[t]=sin(t) (b) y=sin(1:Nsim) (c) y=sapply(1:Nsim,sin) using system.time() with Nsim = 104; 105; 106; 107.
Compare and contrast the speed of a vibrating object and the speed of a wave.
Compare and contrast the speed of a vibrating object and the speed of a wave.
Compare and Contrast rRNA vs. tRNA A site vs. P site vs. E site TOM vs....
Compare and Contrast rRNA vs. tRNA A site vs. P site vs. E site TOM vs. TIM TIC vs. TOC Unfolded protein response (UPR) vs. ER-associated degradation (ERAD)
When the reaction A---->B+C is studied, a plot 1/[A] vs. time gives a straight line with...
When the reaction A---->B+C is studied, a plot 1/[A] vs. time gives a straight line with a positive slope. What is the order of the reaction? A)Zero B)First C)Second D)Third E)More information is needed to determine the order.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT