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

C++版本一

// 需要开启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(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"<

C++版本二

// 需要开启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"<(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 \n");
	}
	printf("time is: %d ms\n", (getTimeUsec() - start_time) / 1000);
	return 0;
}

你可能感兴趣的:(C++,C,linux运维)