#include <array> #include <memory> #include <chrono> #include <iostream> using n
ID: 3903857 • Letter: #
Question
#include <array>
#include <memory>
#include <chrono>
#include <iostream>
using namespace std;
class SuperBigObject {
public:
array<uint64_t, 10000> _data;
};
void SetFirstValue(SuperBigObject object, uint64_t value)
{
object._data[0] = value;
}
// The SuperBigObject holds a large amount of data (10,000 64-bit integers).
// This program calls "SetFirstValue" one million times.
// This progarm is very inefficient because every call to SetFirstValue must copy
// the large object. Furthermore, that large object is stored on the runtime stack!
// OBJECTIVE: Improve both the usage and performance of the "SuperBigObject" by
// moving it to the heap and find a more efficient way to call "SetFirstValue" which
// avoids copying the entire object each time.
// NOTE: You will likely observe an enormous performance improvement on the order of 100x - 1000x
int main()
{
SuperBigObject object;
auto start = chrono::high_resolution_clock::now();
for (size_t i = 0; i < 1000000; ++i)
{
SetFirstValue(object, i);
}
auto seconds = chrono::duration_cast<chrono::duration<float>>(chrono::high_resolution_clock::now() - start);
cout << "The operation took " << seconds.count() << " seconds" << endl;
}
Explanation / Answer
Given below is the modified code..
Before Modification, ouput is
The operation took 9.16125 seconds
After modification, output is
The operation took 0.00677198 seconds
Please do rate the answer if it helped. thank you.
================
#include <array>
#include <memory>
#include <chrono>
#include <iostream>
using namespace std;
class SuperBigObject {
public:
array<uint64_t, 10000> _data;
};
//pass pointer to avoid copying into function parameter
void SetFirstValue(SuperBigObject *object, uint64_t value)
{
object->_data[0] = value;
}
// The SuperBigObject holds a large amount of data (10,000 64-bit integers).
// This program calls "SetFirstValue" one million times.
// This progarm is very inefficient because every call to SetFirstValue must copy
// the large object. Furthermore, that large object is stored on the runtime stack!
// OBJECTIVE: Improve both the usage and performance of the "SuperBigObject" by
// moving it to the heap and find a more efficient way to call "SetFirstValue" which
// avoids copying the entire object each time.
// NOTE: You will likely observe an enormous performance improvement on the order of 100x - 1000x
int main()
{
SuperBigObject *object = new SuperBigObject(); //create on heap
auto start = chrono::high_resolution_clock::now();
for (size_t i = 0; i < 1000000; ++i)
{
SetFirstValue(object, i);
}
auto seconds = chrono::duration_cast<chrono::duration<float> >(chrono::high_resolution_clock::now() - start);
cout << "The operation took " << seconds.count() << " seconds" << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.