linuxでミリ秒タイムスタンプのC++とC言語コードを取得


C++バージョン1
//     c++11  ,g++ test.cpp -std=c++11 -o test
#include 
#include 
using namespace std;

int64_t CurrentTimeMillis()
{
    int64_t timems = std::chrono::duration_cast<:chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    return timems;
}

int main()
{
	int64_t start_time = CurrentTimeMillis();
	for(int i = 0; i < 100; i++)
	{
		std::cout << "hello world"<<:endl std::cout="" is:="" start_time="" ms="" std::endl=""/>

C++バージョン2
//     c++11  ,g++ test.cpp -std=c++11 -o test
#include 
#include  
using namespace std; 

/*
1,000   ns = 1   μs
1,000,000   ns = 1   ms
1,000,000,000   ns = 1  s
*/
int main() 
{ 
    auto start = chrono::high_resolution_clock::now(); 
    for(int i = 0; i < 10000; i++)
	{
		std::cout << "hello world"<<:endl auto="" end="chrono::high_resolution_clock::now();" calculating="" total="" time="" taken="" by="" the="" program.="" double="" time_taken="chrono::duration_cast<chrono::nanoseconds">(end - start).count(); 
  
    time_taken *= 1e-6;//1ms = 1,000,000 ns
    cout << "Time taken by program is : " << time_taken << "ms" << endl;  
    return 0; 
} 

C言語バージョン
#include 
#include 
#include 

long getTimeUsec()
{
    struct timeval t;
    gettimeofday(&t, 0);
    return (long)((long)t.tv_sec * 1000 * 1000 + t.tv_usec);
}

int main()
{
	long start_time = getTimeUsec();
	for(int i = 0; i < 100; i++)
	{
		printf("hello world 
"); } printf("time is: %d ms
", (getTimeUsec() - start_time) / 1000); return 0; }