Timing in C++

Hi all,

In section 26.6.1 (Timing) Stroustrup in its book (Programming Principles And Practice Using C++ 2nd Edition May 2014) declare this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <chrono>
using namespace std;

int main()
{
	int n = 1000000;
	auto t1 = system_clock::now();
	for (int i = 0; i < n; i++)
		i += i;

	auto t2 = system_clock::now();

	cout << "The loop " << n << " times too "
		<< dynamic_cast<milliseconds>(t2 - t1).count() << " milliseconds\n";

   system("pause");
   return 0;
}


When I run it on VS 2017 I get many errors including:

Severity Code Description Project File Line Suppression State
Error C2653 'system_clock': is not a class or namespace name

Severity Code Description Project File Line Suppression State
Error C3861 'now': identifier not found


What is the problem please? It's odd to see a code with these many errors in that book.



Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <chrono>
using namespace std;

int main()
{
	int n = 1000000;
	auto t1 = std::chrono::system_clock::now();
	for (int i = 0; i < n; i++)
		i += i;

	auto t2 = std::chrono::system_clock::now();

	cout 
	<< "The loop " << n << " times too "
	<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << " nanoseconds\n";

   system("pause");
   return 0;
}
closed account (48T7M4Gy)
Also, you can leave out std:: everywhere because you have adopted the un-preferred using namespace std;
Thank you, it worked.
I'm rather astonished why he has written the code that way.
The code is older than the book.
closed account (48T7M4Gy)
My guess is it's #included in a Stroustrups facilities-library-type file. Details are probably somewhere in his fine print or on a web page. Who knows?
Topic archived. No new replies allowed.