linux下获取毫秒时间戳的C++和C语言代码

本文介绍了使用C++和C语言进行时间测量的方法,包括利用C++11标准库中的chrono模块获取高精度时间,以及C语言下通过timeval结构体获取微秒级时间。对比了两种语言中不同方法的时间测量精度。

C++版本一

// 需要开启c++11支持,g++ test.cpp -std=c++11 -o test
#include <iostream>
#include <chrono>
using namespace std;

int64_t CurrentTimeMillis()
{
    int64_t timems = std::chrono::duration_cast<std::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"<<std::endl;
	}
	std::cout << "time is: " <<CurrentTimeMillis() - start_time << " ms" << std::endl;	
}

C++版本二

// 需要开启c++11支持,g++ test.cpp -std=c++11 -o test
#include <iostream>
#include <chrono> 
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"<<std::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 <stdio.h>
#include <time.h>
#include <sys/time.h>

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 \n");
	}
	printf("time is: %d ms\n", (getTimeUsec() - start_time) / 1000);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值