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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xiangxianghehe/article/details/98966034

C++版本

// 需要开启c++11支持,gcc 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语言版本

#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;
}

猜你喜欢

转载自blog.csdn.net/xiangxianghehe/article/details/98966034