/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <chrono>
#include <iostream>
#include <string>
class MyClass
{
public:
std::string GetNameByValue() { return this->Name; };
const std::string& GetNameByReference() { return this->Name; }
std::string GetLocalNameByValue() { std::string name { "This is a name" }; return name; };
std::string Name { "This is a name" };
};
int main()
{
unsigned int repeat = 1e6;
MyClass tester;
char someResult = 0;
// ---------------------------------------------------------
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int i = 0; i < repeat; i++)
{
someResult += tester.GetLocalNameByValue()[5];
}
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << someResult <<" Get local by reference: " << elapsed.count()/repeat << " s\n";
// ---------------------------------------------------------
start = std::chrono::high_resolution_clock::now();
for (unsigned int i = 0; i < repeat; i++)
{
someResult += tester.GetNameByValue()[5];
}
finish = std::chrono::high_resolution_clock::now();
elapsed = finish - start;
std::cout << someResult <<" Get member by value: " << elapsed.count()/repeat << " s\n";
// ---------------------------------------------------------
start = std::chrono::high_resolution_clock::now();
for (unsigned int i = 0; i < repeat; i++)
{
someResult += tester.GetNameByReference()[5];
}
finish = std::chrono::high_resolution_clock::now();
elapsed = finish - start;
std::cout << someResult <<" Get member by reference: " << elapsed.count()/repeat << " s\n";
return 0;
}